"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  StatusBadge,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { IconLock, IconShield } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";
import NotifySettingsCard from "@/components/NotifySettingsCard";
import AnalyticsCard from "@/components/AnalyticsCard";

interface Account {
  id: number;
  name: string;
  email: string | null;
  username: string | null;
  role: string;
  institutionId: number | null;
  createdAt: string;
  institution: {
    name: string;
    type: string;
    status: string;
    parentName: string | null;
  } | null;
}

const ROLE_BADGES: Record<string, string> = {
  SUPER_ADMIN: "badge-primary",
  INSTITUTION_ADMIN: "badge-dark",
  STUDENT: "badge-success",
  TEACHER: "badge-info",
  PARENT: "badge-warning",
  STAFF: "badge-secondary",
};

export default function CentralAccountsPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ accounts: Account[] }>("/api/central/accounts");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [roleFilter, setRoleFilter] = useState("");

  // Reset-password modal
  const [resetOpen, setResetOpen] = useState<Account | null>(null);
  const [newPassword, setNewPassword] = useState("");
  const [resetSaving, setResetSaving] = useState(false);

  function openReset(account: Account) {
    setResetOpen(account);
    setNewPassword("");
  }

  async function saveReset() {
    if (!resetOpen) return;
    if (!(await emsConfirm({ message: t.central.accountsPage.resetConfirm, danger: true }))) return;
    setResetSaving(true);
    try {
      await api(`/api/central/accounts/${resetOpen.id}`, {
        method: "PATCH",
        body: JSON.stringify({ password: newPassword }),
      });
      setResetOpen(null);
      setNewPassword("");
      setMessage({ type: "success", text: t.central.accountsPage.passwordReset });
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setResetSaving(false);
    }
  }

  const accounts = useMemo(() => {
    const all = data?.accounts ?? [];
    return roleFilter ? all.filter((a) => a.role === roleFilter) : all;
  }, [data, roleFilter]);
  const accountsPager = usePagination(accounts, 10);

  const roleOptions = [
    "SUPER_ADMIN",
    "INSTITUTION_ADMIN",
    "STUDENT",
    "TEACHER",
    "PARENT",
    "STAFF",
  ];

  return (
    <div>
      <PageHeader
        title={t.central.accountsPage.title}
        subtitle={t.central.accountsPage.subtitle}
      />

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

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : accounts.length === 0 ? (
        <div className="card">
          <EmptyState icon={<IconShield />} title={t.central.accountsPage.noAccounts} />
        </div>
      ) : (
        <div className="card">
          <div className="card-header">
            <div style={{ maxWidth: 220 }}>
              <Select
                wrapperClassName="form-group mb-0"
                value={roleFilter}
                onChange={(e) => setRoleFilter(e.target.value)}
              >
                <option value="">{t.common.all} — {t.central.accountsPage.role}</option>
                {roleOptions.map((r) => (
                  <option key={r} value={r}>
                    {t.status[r as keyof typeof t.status]}
                  </option>
                ))}
              </Select>
            </div>
          </div>
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.central.accountsPage.loginEmail}</th>
                  <th>{t.central.accountsPage.role}</th>
                  <th>{t.common.institution}</th>
                  <th>{t.common.createdAt}</th>
                  <th className="text-end">{t.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {accountsPager.paged.map((account) => (
                  <tr key={account.id}>
                    <td>
                      <div className="media align-items-center gap-3">
                        <span
                          className="rounded-circle d-flex align-items-center justify-content-center f-w-800 ems-fs-12"
                          style={{ width: 40, height: 40, background: "rgba(36,105,92,0.14)", color: "#24695c" }}
                        >
                          {account.name.slice(0, 2).toUpperCase()}
                        </span>
                        <div className="media-body">
                          <h6 className="mb-0 f-w-700">{account.name}</h6>
                          {account.email ? (
                            <span className="ems-fs-11 text-muted">{account.email}</span>
                          ) : account.username ? (
                            <code className="ems-invoice-badge">{account.username}</code>
                          ) : (
                            <span className="ems-fs-11 text-muted">—</span>
                          )}
                        </div>
                      </div>
                    </td>
                    <td>
                      <span className={`badge ${ROLE_BADGES[account.role] ?? "badge-secondary"}`}>
                        {t.status[account.role as keyof typeof t.status] ?? account.role}
                      </span>
                    </td>
                    <td>
                      {account.institution ? (
                        <div>
                          <p className="mb-1 f-w-600 ems-fs-13">{account.institution.name}</p>
                          <div className="d-flex align-items-center gap-2">
                            <span className={`ems-type-pill ems-type-${account.institution.type}`}>
                              {t.types[account.institution.type as keyof typeof t.types]}
                            </span>
                            {account.institution.parentName && (
                              <span className="badge badge-secondary">
                                {t.central.institutionsPage.branchOf}: {account.institution.parentName}
                              </span>
                            )}
                          </div>
                          <div className="mt-1">
                            <StatusBadge
                              status={account.institution.status}
                              label={t.status[account.institution.status as keyof typeof t.status]}
                            />
                          </div>
                        </div>
                      ) : (
                        <span className="badge badge-primary">{t.central.accountsPage.centralController}</span>
                      )}
                    </td>
                    <td>
                      <span className="ems-fs-12 text-muted">{formatDate(account.createdAt, locale)}</span>
                    </td>
                    <td className="text-end">
                      <Button size="sm" variant="secondary" onClick={() => openReset(account)}>
                        <IconLock className="svg-16" />
                        <span className="ms-1 d-none d-lg-inline">{t.central.accountsPage.resetPassword}</span>
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <Pagination {...accountsPager} onPageChange={accountsPager.setPage} onSizeChange={accountsPager.setSize} />
        </div>
      )}

      {/* Reset password modal */}
      <Modal
        open={!!resetOpen}
        onClose={() => setResetOpen(null)}
        title={`${t.central.accountsPage.resetPassword} — ${resetOpen?.name ?? ""}`}
      >
        {resetOpen && (
          <>
            <p className="ems-fs-12 text-muted">
              {t.central.accountsPage.loginEmail}:{" "}
              <span className="f-w-600 text-dark">{resetOpen.email ?? resetOpen.username}</span>
            </p>
            <Input
              label={t.central.accountsPage.newPassword}
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
            />
            <p className="ems-fs-11 text-muted mb-3">{t.central.accountsPage.resetHint}</p>
            <div className="d-flex justify-content-end gap-2">
              <Button variant="secondary" onClick={() => setResetOpen(null)}>
                {t.common.cancel}
              </Button>
              <Button onClick={saveReset} loading={resetSaving} disabled={newPassword.length < 6}>
                {t.central.accountsPage.resetPassword}
              </Button>
            </div>
          </>
        )}
      </Modal>

      {/* Central Email/SMS (OTP) delivery credentials */}
      <div className="mt-4">
        <NotifySettingsCard scope="CENTRAL" />
      </div>

      {/* Google Analytics control panel */}
      <div className="mt-4">
        <AnalyticsCard />
      </div>
    </div>
  );
}
