"use client";

import { useEffect, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import { Alert, Button, EmptyState, Input, Modal, PageLoader, Select } from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { IconEdit, IconPlus, IconTrash, IconWallet } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

/* Control Panel card: the institution's receiving accounts — mobile banking
   wallets, bank accounts, cash-office/other info. Shown to members on
   their Fees page ("where to pay"). */

interface Account {
  id: number;
  type: "MOBILE" | "BANK" | "OTHER";
  provider: string | null;
  accountType: string | null;
  label: string;
  accountName: string | null;
  accountNumber: string;
  branch: string | null;
  routingNo: string | null;
  note: string | null;
  isActive: boolean;
  sortOrder: number;
}

const emptyForm = {
  type: "MOBILE" as "MOBILE" | "BANK" | "OTHER",
  provider: "BKASH",
  accountType: "PERSONAL",
  label: "",
  accountName: "",
  accountNumber: "",
  branch: "",
  routingNo: "",
  note: "",
  isActive: true,
};

export default function CollectionAccountsCard() {
  const { t, locale } = useLang();
  const a = t.portal.controlPanelPage;
  const { data, loading, reload } = useApi<{ accounts: Account[] }>("/api/portal/collection-accounts");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [modal, setModal] = useState(false);
  const [editing, setEditing] = useState<Account | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (editing) {
      setForm({
        type: editing.type,
        provider: editing.provider ?? "BKASH",
        accountType: editing.accountType ?? "PERSONAL",
        label: editing.label,
        accountName: editing.accountName ?? "",
        accountNumber: editing.accountNumber,
        branch: editing.branch ?? "",
        routingNo: editing.routingNo ?? "",
        note: editing.note ?? "",
        isActive: editing.isActive,
      });
    } else {
      setForm(emptyForm);
    }
  }, [editing, modal]);

  function openCreate() {
    setEditing(null);
    setModal(true);
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      if (editing) {
        await api(`/api/portal/collection-accounts/${editing.id}`, { method: "PUT", body: JSON.stringify(form) });
        setMessage({ type: "success", text: a.caUpdated });
      } else {
        await api("/api/portal/collection-accounts", { method: "POST", body: JSON.stringify(form) });
        setMessage({ type: "success", text: a.caCreated });
      }
      setModal(false);
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setSaving(false);
    }
  }

  async function remove(acc: Account) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/portal/collection-accounts/${acc.id}`, { method: "DELETE" });
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  const typeBadge = (acc: Account) =>
    acc.type === "MOBILE" ? (
      <span className="badge badge-soft-teal">{a.caMobile}</span>
    ) : acc.type === "BANK" ? (
      <span className="badge badge-info">{a.caBank}</span>
    ) : (
      <span className="badge badge-secondary">{a.caOther}</span>
    );

  return (
    <div className="card">
      <div className="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
        <div>
          <h5 className="mb-0 f-w-700">{a.caTitle}</h5>
          <p className="mb-0 ems-fs-12 text-muted">{a.caSubtitle}</p>
        </div>
        <Button size="sm" onClick={openCreate}>
          <IconPlus className="svg-14" />
          <span className="ms-1">{a.caAdd}</span>
        </Button>
      </div>

      {message && (
        <div className="px-3 pt-3">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      <div className="card-body">
        {loading ? (
          <PageLoader text={t.common.loading} />
        ) : (data?.accounts ?? []).length === 0 ? (
          <EmptyState icon={<IconWallet />} title={a.caEmpty} subtitle={a.caEmptyHint} />
        ) : (
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.common.type}</th>
                  <th>{a.caLabelCol}</th>
                  <th>{a.caNumberCol}</th>
                  <th>{a.caNameCol}</th>
                  <th className="text-center">{t.common.status}</th>
                  <th className="text-end">{t.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {data!.accounts.map((acc) => (
                  <tr key={acc.id} className={acc.isActive ? "" : "opacity-50"}>
                    <td>{typeBadge(acc)}</td>
                    <td className="f-w-600">
                      {acc.type === "MOBILE" && acc.provider
                        ? t.methods[acc.provider as keyof typeof t.methods] ?? acc.label
                        : acc.label}
                      {acc.type === "MOBILE" && acc.accountType && (
                        <span className="badge badge-secondary ms-1">
                          {acc.accountType === "MERCHANT" ? a.caMerchant : a.caPersonal}
                        </span>
                      )}
                    </td>
                    <td><code className="ems-invoice-badge">{acc.accountNumber}</code></td>
                    <td className="ems-fs-12 text-muted">
                      {acc.accountName ?? "—"}
                      {acc.branch ? ` · ${acc.branch}` : ""}
                    </td>
                    <td className="text-center">
                      <span className={`badge ${acc.isActive ? "badge-success" : "badge-secondary"}`}>
                        {acc.isActive ? t.common.active : t.common.inactive}
                      </span>
                    </td>
                    <td className="text-end">
                      <div className="d-inline-flex gap-1">
                        <Button size="sm" variant="secondary" onClick={() => { setEditing(acc); setModal(true); }}>
                          <IconEdit className="svg-14" />
                        </Button>
                        <Button size="sm" variant="secondary" onClick={() => remove(acc)}>
                          <IconTrash className="svg-14" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {!loading && (data?.accounts ?? []).length > 0 && (
          <p className="ems-fs-11 text-muted mb-0 mt-3">{a.caMemberHint}</p>
        )}
      </div>

      {/* add / edit modal */}
      <Modal open={modal} onClose={() => setModal(false)} title={editing ? a.caEdit : a.caAdd}>
        <form className="theme-form" onSubmit={save}>
          <Select
            label={t.common.type}
            value={form.type}
            onChange={(e) => setForm({ ...form, type: e.target.value as typeof form.type })}
          >
            <option value="MOBILE">{a.caMobile}</option>
            <option value="BANK">{a.caBank}</option>
            <option value="OTHER">{a.caOther}</option>
          </Select>

          {form.type === "MOBILE" && (
            <div className="row g-2">
              <div className="col-6">
                <Select label={a.caProvider} value={form.provider} onChange={(e) => setForm({ ...form, provider: e.target.value })}>
                  {["BKASH", "NAGAD", "ROCKET", "UPAY", "OTHER"].map((p) => (
                    <option key={p} value={p}>{t.methods[p as keyof typeof t.methods] ?? p}</option>
                  ))}
                </Select>
              </div>
              <div className="col-6">
                <Select label={a.caAccountType} value={form.accountType} onChange={(e) => setForm({ ...form, accountType: e.target.value })}>
                  <option value="PERSONAL">{a.caPersonal}</option>
                  <option value="MERCHANT">{a.caMerchant}</option>
                </Select>
              </div>
            </div>
          )}

          {form.type !== "OTHER" && (
            <Input
              label={form.type === "BANK" ? `${a.caBankName} *` : a.caLabel}
              value={form.label}
              placeholder={form.type === "BANK" ? "Dutch Bangla Bank" : locale === "bn" ? "প্রতিষ্ঠানের নাম" : "Display label"}
              onChange={(e) => setForm({ ...form, label: e.target.value })}
            />
          )}

          {form.type !== "OTHER" && (
            <Input
              label={form.type === "MOBILE" ? `${a.caWalletNo} *` : `${a.caAccountNo} *`}
              value={form.accountNumber}
              placeholder={form.type === "MOBILE" ? "01XXXXXXXXX" : "1234567890"}
              onChange={(e) => setForm({ ...form, accountNumber: e.target.value })}
            />
          )}

          {form.type === "BANK" && (
            <div className="row g-2">
              <div className="col-6">
                <Input label={a.caBranch} value={form.branch} onChange={(e) => setForm({ ...form, branch: e.target.value })} />
              </div>
              <div className="col-6">
                <Input label={a.caRouting} value={form.routingNo} onChange={(e) => setForm({ ...form, routingNo: e.target.value })} />
              </div>
            </div>
          )}

          <Input
            label={form.type === "BANK" ? a.caAccountName : a.caHolder}
            value={form.accountName}
            onChange={(e) => setForm({ ...form, accountName: e.target.value })}
          />

          {form.type === "OTHER" && (
            <Input
              label={`${t.common.name} *`}
              value={form.label}
              placeholder={locale === "bn" ? "যেমন: অফিস ক্যাশ কাউন্টার" : "e.g. School Cash Counter"}
              onChange={(e) => setForm({ ...form, label: e.target.value })}
            />
          )}

          <Input
            label={t.common.note}
            value={form.note}
            placeholder={a.caNoteHint}
            onChange={(e) => setForm({ ...form, note: e.target.value })}
          />

          <div className="form-check form-switch mb-3">
            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="ca-active"
              checked={form.isActive}
              onChange={(e) => setForm({ ...form, isActive: e.target.checked })}
            />
            <label className="form-check-label ems-fs-12 f-w-600" htmlFor="ca-active">{t.common.active}</label>
          </div>

          <div className="d-flex justify-content-end gap-2">
            <Button type="button" variant="secondary" onClick={() => setModal(false)}>{t.common.cancel}</Button>
            <Button type="submit" loading={saving}>{t.common.save}</Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
