// Dashboard page
const Dashboard = ({ t, lang, toast }) => {
  const D = window.MOCK_DATA;
  const [filterType, setFilterType] = React.useState("all");
  const [filterBuilding, setFilterBuilding] = React.useState("all");
  const [filterMonth, setFilterMonth] = React.useState("may");
  const [filterYear, setFilterYear] = React.useState("2026");

  const months = lang === "th" ? D.monthly.months_th : D.monthly.months;

  const kpis = [
    { id: "elec",  icon: "bolt",    label: t("kpi_electricity"), value: 51200, unit: t("units_kwh"),  delta: +5.1, series: D.monthly.elec },
    { id: "water", icon: "droplet", label: t("kpi_water"),       value: 2180,  unit: t("units_m3"),   delta: +6.3, series: D.monthly.water },
    { id: "net",   icon: "wifi",    label: t("kpi_internet"),    value: 1000,  unit: t("units_mbps"), delta: 0,     series: D.monthly.net },
    { id: "phone", icon: "phone",   label: t("kpi_phone"),       value: 3280,  unit: t("units_min"),  delta: +4.1, series: D.monthly.phone },
  ];

  const breakdown = [
    { label: t("kpi_electricity"), value: 51200 * 4.42,  color: "#EA580C" },
    { label: t("kpi_water"),       value: 2180  * 18.5,  color: "#0EA5E9" },
    { label: t("kpi_internet"),    value: 1290,          color: "#10B981" },
    { label: t("kpi_phone"),       value: 3280 * 0.85,   color: "#A855F7" },
  ];

  const filtered = D.recent.filter(r => (filterType === "all" || r.type === filterType));

  const exportCSV = () => {
    toast(t("toast_csv_exported"));
  };

  const typeOf = (id) => D.utility_types.find(x => x.id === id);
  const meterOf = (id) => D.meters.find(x => x.id === id);

  return (
    <div className="page" data-screen-label="Dashboard">
      <div className="page-head">
        <div>
          <h1 className="page-title">{t("dash_title")}</h1>
          <p className="page-sub">{t("dash_sub")}</p>
        </div>
        <div className="header-actions">
          <button className="btn" onClick={exportCSV}><Icon name="download" className="ico" />{t("export_csv")}</button>
          <button className="btn accent"><Icon name="plus" className="ico" />{t("new_reading")}</button>
        </div>
      </div>

      <div className="kpi-grid">
        {kpis.map((k) => {
          const ut = D.utility_types.find(u => u.id === k.id);
          return (
            <div key={k.id} className="kpi">
              <div className="kpi-label">
                <Icon name={k.icon} size={14} style={{ color: ut.color }} />
                <span>{k.label}</span>
              </div>
              <div className="kpi-value num">{k.value.toLocaleString()} <span className="unit">{k.unit}</span></div>
              <div className="kpi-delta">
                {k.delta > 0 ? <span className="up">▲ {k.delta}%</span> :
                 k.delta < 0 ? <span className="down">▼ {Math.abs(k.delta)}%</span> :
                 <span>—</span>}
                <span>{t("kpi_vs_prev")}</span>
              </div>
              <div className="kpi-spark">
                <Spark values={k.series} color={ut.color} width={120} height={36} />
              </div>
            </div>
          );
        })}
      </div>

      <div className="row two-thirds">
        <div className="card">
          <div className="card-head">
            <div>
              <h3 className="card-title">{t("chart_monthly")}</h3>
              <p className="card-sub">{t("chart_monthly_sub")}</p>
            </div>
            <div style={{ display: "flex", gap: 12 }}>
              {D.utility_types.map(ut => (
                <div key={ut.id} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12 }}>
                  <span style={{ width: 8, height: 8, background: ut.color, borderRadius: 2 }}></span>
                  <span style={{ color: "var(--text-2)" }}>{lang === "th" ? ut.label_th : ut.label_en}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="card-body">
            <LineChart
              labels={months}
              series={[
                { name: t("kpi_electricity"), values: D.monthly.elec.map(v => v / 1000), color: "#EA580C", fill: true },
                { name: t("kpi_water"),       values: D.monthly.water.map(v => v / 50),  color: "#0EA5E9" },
                { name: t("kpi_phone"),       values: D.monthly.phone.map(v => v / 50),  color: "#A855F7" },
              ]}
              yFormat={(v) => v + "k"}
            />
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div>
              <h3 className="card-title">{t("chart_breakdown")}</h3>
              <p className="card-sub">{t("chart_breakdown_sub")}</p>
            </div>
          </div>
          <div className="card-body" style={{ display: "flex", alignItems: "center", gap: 18, justifyContent: "center" }}>
            <DonutChart data={breakdown} size={170} thickness={20} />
            <div className="legend" style={{ minWidth: 130 }}>
              {breakdown.map((b, i) => (
                <div key={i} className="legend-row">
                  <span className="swatch" style={{ background: b.color }}></span>
                  <span className="lbl">{b.label}</span>
                  <span className="val num">{Math.round(b.value).toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="card-foot">
            <span>{lang === "en" ? "Total" : "รวม"}</span>
            <span className="num cell-strong">{Math.round(breakdown.reduce((s, b) => s + b.value, 0)).toLocaleString()} {t("units_thb")}</span>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 14 }}>
        <div className="card-head">
          <div>
            <h3 className="card-title">{t("recent_title")}</h3>
            <p className="card-sub">{t("recent_sub")}</p>
          </div>
          <button className="btn subtle" onClick={exportCSV}><Icon name="download" className="ico" />{t("export_csv")}</button>
        </div>
        <div className="filter-bar">
          <Icon name="filter" style={{ color: "var(--text-3)" }} />
          <label>{t("filter_type")}</label>
          <select value={filterType} onChange={(e) => setFilterType(e.target.value)}>
            <option value="all">{t("filter_all")}</option>
            {D.utility_types.map(ut => (
              <option key={ut.id} value={ut.id}>{lang === "th" ? ut.label_th : ut.label_en}</option>
            ))}
          </select>
          <label>{t("filter_building")}</label>
          <select value={filterBuilding} onChange={(e) => setFilterBuilding(e.target.value)}>
            <option value="all">{t("filter_all")}</option>
            {D.buildings.map(b => <option key={b.id} value={b.id}>{lang === "th" ? b.label_th : b.label_en}</option>)}
          </select>
          <label>{t("filter_month")}</label>
          <select value={filterMonth} onChange={(e) => setFilterMonth(e.target.value)}>
            {months.map((m, i) => <option key={i} value={m.toLowerCase()}>{m}</option>)}
          </select>
          <label>{t("filter_year")}</label>
          <select value={filterYear} onChange={(e) => setFilterYear(e.target.value)}>
            <option value="2026">2026</option>
            <option value="2025">2025</option>
            <option value="2024">2024</option>
          </select>
          <span className="spacer"></span>
          <span style={{ fontSize: 12, color: "var(--text-3)" }}>
            {filtered.length} {lang === "en" ? "records" : "รายการ"}
          </span>
        </div>
        <div className="table-wrap">
          <table className="data">
            <thead>
              <tr>
                <th>{t("col_date")}</th>
                <th>{t("col_meter")}</th>
                <th>{t("col_type")}</th>
                <th style={{ textAlign: "right" }}>{t("col_reading")}</th>
                <th style={{ textAlign: "right" }}>{t("col_usage")}</th>
                <th>{t("col_submitted_by")}</th>
                <th>{t("col_status")}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, i) => {
                const ut = typeOf(r.type);
                const m = meterOf(r.meter);
                return (
                  <tr key={i}>
                    <td className="cell-mono">{r.date}</td>
                    <td>
                      <div className="cell-strong">{r.meter}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{m ? (lang === "th" ? m.label_th : m.label_en) : ""}</div>
                    </td>
                    <td>
                      <span className="type-badge">
                        <span className="swatch" style={{ background: ut.color }}></span>
                        {lang === "th" ? ut.label_th : ut.label_en}
                      </span>
                    </td>
                    <td className="cell-num" style={{ textAlign: "right" }}>{r.reading.toLocaleString()}</td>
                    <td className="cell-num cell-strong" style={{ textAlign: "right" }}>
                      {r.usage.toLocaleString()} <span style={{ color: "var(--text-3)", fontWeight: 400 }}>{lang === "th" ? ut.unit_th : ut.unit_en}</span>
                    </td>
                    <td>{r.by}</td>
                    <td>
                      <span className={"pill " + r.status}>
                        <span className="pdot"></span>
                        {t("status_" + r.status)}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

window.Dashboard = Dashboard;
