// Utility usage submission form
const FormPage = ({ t, lang, toast }) => {
  const D = window.MOCK_DATA;
  const [typeId, setTypeId] = React.useState("elec");
  const [meterId, setMeterId] = React.useState("ME-001");
  const [date, setDate] = React.useState("2026-05-15");
  const [current, setCurrent] = React.useState(48210);
  const [notes, setNotes] = React.useState("");
  const [photoUrl, setPhotoUrl] = React.useState(null);
  const [photoName, setPhotoName] = React.useState("");
  const [dragOver, setDragOver] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const fileRef = React.useRef(null);

  const hasPhoto = !!photoUrl;
  const readFile = (file) => {
    if (!file || !file.type.startsWith("image/")) {
      toast(lang === "en" ? "Please choose an image file" : "กรุณาเลือกไฟล์รูปภาพ");
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      setPhotoUrl(e.target.result);
      setPhotoName(file.name);
    };
    reader.readAsDataURL(file);
  };
  const clearPhoto = () => { setPhotoUrl(null); setPhotoName(""); if (fileRef.current) fileRef.current.value = ""; };

  const meters = D.meters.filter(m => m.type === typeId);
  const meter = D.meters.find(m => m.id === meterId) || meters[0];
  const type = D.utility_types.find(u => u.id === typeId);
  const previous = meter ? meter.last : 0;
  const usage = Math.max(0, current - previous);

  React.useEffect(() => {
    // when type changes, pick a meter of that type
    const m = D.meters.find(mm => mm.type === typeId);
    if (m) {
      setMeterId(m.id);
      setCurrent(m.last + Math.round(Math.random() * 2000 + 500));
    }
  }, [typeId]);

  const submit = () => {
    if (!hasPhoto) {
      toast(lang === "en" ? "Photo of meter is required" : "ต้องแนบรูปถ่ายมิเตอร์");
      return;
    }
    setSubmitted(true);
    toast(t("form_submitted"));
  };

  if (submitted) {
    return (
      <div className="page" data-screen-label="Form">
        <div style={{ maxWidth: 520, margin: "80px auto 0", textAlign: "center" }}>
          <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent)", margin: "0 auto 16px", display: "grid", placeItems: "center" }}>
            <Icon name="check" size={26} />
          </div>
          <h1 className="page-title" style={{ marginBottom: 6 }}>{t("form_submitted")}</h1>
          <p className="page-sub" style={{ margin: "0 auto 24px" }}>{t("form_submitted_sub")}</p>
          <div className="card" style={{ textAlign: "left", marginBottom: 16 }}>
            <div className="card-body" style={{ padding: "16px 18px" }}>
              <div className="login-art-row"><span className="login-art-label">{t("form_utility_type")}</span><span className="login-art-val">{lang === "th" ? type.label_th : type.label_en}</span></div>
              <div className="login-art-row"><span className="login-art-label">{t("form_meter")}</span><span className="login-art-val">{meter.id}</span></div>
              <div className="login-art-row"><span className="login-art-label">{t("form_reading_date")}</span><span className="login-art-val">{date}</span></div>
              <div className="login-art-row"><span className="login-art-label">{t("form_current")}</span><span className="login-art-val">{current.toLocaleString()}</span></div>
              <div className="login-art-row"><span className="login-art-label">{t("form_calc_usage")}</span><span className="login-art-val" style={{ color: "var(--accent)" }}>{usage.toLocaleString()} {lang === "th" ? type.unit_th : type.unit_en}</span></div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
            <button className="btn" onClick={() => { setSubmitted(false); clearPhoto(); }}>
              <Icon name="plus" className="ico" />
              {lang === "en" ? "Submit another" : "บันทึกอีกรายการ"}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="Form">
      <div className="page-head">
        <div>
          <h1 className="page-title">{t("form_title")}</h1>
          <p className="page-sub">{t("form_sub")}</p>
        </div>
      </div>

      <div className="row" style={{ gridTemplateColumns: "1.3fr 1fr" }}>
        <div className="card">
          <div className="card-body" style={{ padding: 22, display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="field-row">
              <div className="field">
                <label>{t("form_utility_type")}<span className="req">*</span></label>
                <select value={typeId} onChange={(e) => setTypeId(e.target.value)}>
                  {D.utility_types.map(u => <option key={u.id} value={u.id}>{lang === "th" ? u.label_th : u.label_en}</option>)}
                </select>
              </div>
              <div className="field">
                <label>{t("form_meter")}<span className="req">*</span></label>
                <select value={meterId} onChange={(e) => setMeterId(e.target.value)}>
                  {meters.map(m => <option key={m.id} value={m.id}>{m.id} · {lang === "th" ? m.label_th : m.label_en}</option>)}
                </select>
              </div>
            </div>

            <div className="field-row">
              <div className="field">
                <label>{t("form_reading_date")}<span className="req">*</span></label>
                <input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
              </div>
              <div className="field">
                <label>{t("form_previous")}</label>
                <input type="text" value={previous.toLocaleString()} readOnly style={{ background: "var(--panel-2)", color: "var(--text-3)" }} />
              </div>
            </div>

            <div className="field-row">
              <div className="field">
                <label>{t("form_current")}<span className="req">*</span></label>
                <input type="number" value={current} onChange={(e) => setCurrent(Number(e.target.value))} />
                <span className="hint">{lang === "th" ? type.unit_th : type.unit_en}</span>
              </div>
              <div className="field">
                <label>{t("form_calc_usage")}</label>
                <div style={{
                  border: "1px solid var(--accent-line)",
                  background: "var(--accent-soft)",
                  borderRadius: 8,
                  padding: "8px 12px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                }}>
                  <span style={{ fontSize: 18, fontWeight: 700, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>
                    {usage.toLocaleString()}
                  </span>
                  <span style={{ fontSize: 12, color: "var(--text-3)" }}>
                    {lang === "th" ? type.unit_th : type.unit_en}
                  </span>
                </div>
              </div>
            </div>

            <div className="field">
              <label>{t("form_notes")}</label>
              <textarea placeholder={t("form_notes_ph")} value={notes} onChange={(e) => setNotes(e.target.value)} />
            </div>

            <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
              <button className="btn"><Icon name="sheet" className="ico" />{t("form_save_draft")}</button>
              <button className="btn accent" onClick={submit}>
                <Icon name="check" className="ico" />
                {t("form_submit")}
              </button>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div>
              <h3 className="card-title">{t("form_photo")}<span style={{ color: "var(--accent)" }}>*</span></h3>
              <p className="card-sub">{t("form_photo_help")}</p>
            </div>
          </div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <input
              ref={fileRef}
              type="file"
              accept="image/*"
              style={{ display: "none" }}
              onChange={(e) => readFile(e.target.files[0])}
            />
            {!hasPhoto ? (
              <div className={"dropzone" + (dragOver ? " dragover" : "")}
                   onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                   onDragLeave={() => setDragOver(false)}
                   onDrop={(e) => { e.preventDefault(); setDragOver(false); readFile(e.dataTransfer.files[0]); }}
                   onClick={() => fileRef.current && fileRef.current.click()}
                   style={{ cursor: "pointer" }}>
                <Icon name="image" className="file-icon" />
                <div style={{ fontSize: 13.5, color: "var(--text-2)" }}>
                  {t("form_photo_drop")} <span className="browse">{t("form_photo_browse")}</span>
                </div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>JPG, PNG, HEIC · max 10 MB</div>
              </div>
            ) : (
              <div className="photo-preview">
                <img src={photoUrl} alt={photoName}
                     style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                <div style={{
                  position: "absolute", left: 8, bottom: 8,
                  background: "rgba(0,0,0,0.65)", color: "#fff",
                  borderRadius: 6, padding: "3px 8px", fontSize: 11,
                  fontFamily: "var(--font-mono)", maxWidth: "70%",
                  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"
                }}>{photoName}</div>
                <button onClick={clearPhoto} style={{
                  position: "absolute", top: 8, right: 8,
                  border: "none", background: "rgba(0,0,0,0.65)", color: "#fff",
                  borderRadius: 6, padding: "4px 8px", fontSize: 11, cursor: "pointer",
                  display: "flex", alignItems: "center", gap: 4
                }}><Icon name="trash" size={12} />{t("delete")}</button>
              </div>
            )}
            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn" style={{ flex: 1, justifyContent: "center" }}
                      onClick={() => fileRef.current && fileRef.current.click()}>
                <Icon name="upload" className="ico" />
                {hasPhoto ? (lang === "en" ? "Replace" : "เปลี่ยนรูป") : t("form_photo_browse")}
              </button>
              <button className="btn" style={{ flex: 1, justifyContent: "center" }}
                      onClick={() => {
                        // Mobile browsers open camera with capture attr
                        if (fileRef.current) {
                          fileRef.current.setAttribute("capture", "environment");
                          fileRef.current.click();
                          setTimeout(() => fileRef.current && fileRef.current.removeAttribute("capture"), 1000);
                        }
                      }}>
                <Icon name="camera" className="ico" />
                {t("form_photo_camera")}
              </button>
            </div>
            <div style={{ display: "flex", gap: 8, padding: "10px 12px", background: "var(--panel-2)", border: "1px solid var(--line-soft)", borderRadius: 8 }}>
              <Icon name="folder" style={{ color: "var(--text-3)", flexShrink: 0, marginTop: 1 }} />
              <div style={{ fontSize: 11.5, color: "var(--text-3)", lineHeight: 1.5 }}>
                {lang === "en"
                  ? <>Uploads sync to Google Drive folder <b style={{ color: "var(--text-2)" }}>/Verena/Utility-Meters/2026/{type.label_en}</b></>
                  : <>อัปโหลดไปยังโฟลเดอร์ Google Drive <b style={{ color: "var(--text-2)" }}>/Verena/Utility-Meters/2026/{type.label_th}</b></>}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.FormPage = FormPage;
