"use client";

import { useEffect, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import { Alert, Button, Card, Input, PageHeader, StatusBadge } from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { IconUser } from "@/components/icons";

interface Profile {
  id: number;
  name: string;
  email: string | null;
  role: string;
  lastLoginAt: string | null;
  createdAt: string;
}

export default function CentralProfilePage() {
  const { t } = useLang();
  const p = t.central.profilePage;
  const { data, reload } = useApi<{ profile: Profile }>("/api/central/profile");

  const [form, setForm] = useState({ name: "", email: "" });
  const [loaded, setLoaded] = useState(false);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const [pw, setPw] = useState({ currentPassword: "", newPassword: "", confirmPassword: "" });
  const [pwSaving, setPwSaving] = useState(false);
  const [pwMessage, setPwMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    if (data?.profile && !loaded) {
      setForm({ name: data.profile.name, email: data.profile.email ?? "" });
      setLoaded(true);
    }
  }, [data, loaded]);

  /** Update the central administrator's own name / sign-in email. */
  async function saveProfile() {
    setSaving(true);
    setMessage(null);
    try {
      await api("/api/central/profile", { method: "PUT", body: JSON.stringify(form) });
      setMessage({ type: "success", text: p.updated });
      reload();
    } catch (err) {
      const msg = err instanceof Error ? err.message : "";
      setMessage({
        type: "error",
        text: msg === "EMAIL_EXISTS" ? t.auth.emailExists : msg || t.common.tryAgain,
      });
    } finally {
      setSaving(false);
    }
  }

  /** Rotate the central administrator's password (current password proof). */
  async function changePassword() {
    setPwMessage(null);
    if (pw.newPassword !== pw.confirmPassword) {
      setPwMessage({ type: "error", text: t.auth.passwordMismatch });
      return;
    }
    if (pw.newPassword.length < 6) {
      setPwMessage({ type: "error", text: t.common.minPassword });
      return;
    }
    setPwSaving(true);
    try {
      await api("/api/central/profile", {
        method: "POST",
        body: JSON.stringify({ currentPassword: pw.currentPassword, newPassword: pw.newPassword }),
      });
      setPw({ currentPassword: "", newPassword: "", confirmPassword: "" });
      setPwMessage({ type: "success", text: p.passwordUpdated });
    } catch (err) {
      const msg = err instanceof Error ? err.message : "";
      setPwMessage({
        type: "error",
        text: msg === "WRONG_PASSWORD" ? p.wrongPassword : msg || t.common.tryAgain,
      });
    } finally {
      setPwSaving(false);
    }
  }

  const fmt = (iso: string | null) =>
    iso ? new Date(iso).toLocaleString() : p.never;

  return (
    <>
      <PageHeader title={p.title} subtitle={p.subtitle} />

      <div className="row g-4">
        {/* -------- credential information -------- */}
        <div className="col-12 col-xl-4">
          <Card title={p.infoTitle} icon={<IconUser className="svg-18" />}>
            {data?.profile ? (
              <dl className="mb-0">
                <dt className="f-w-600 text-dark">{t.common.name}</dt>
                <dd className="mb-3">{data.profile.name}</dd>
                <dt className="f-w-600 text-dark">{t.common.email}</dt>
                <dd className="mb-3">{data.profile.email}</dd>
                <dt className="f-w-600 text-dark">{p.role}</dt>
                <dd className="mb-3">
                  <StatusBadge status="ACTIVE" label={data.profile.role} />
                </dd>
                <dt className="f-w-600 text-dark">{p.lastLogin}</dt>
                <dd className="mb-3">{fmt(data.profile.lastLoginAt)}</dd>
                <dt className="f-w-600 text-dark">{p.createdAt}</dt>
                <dd className="mb-0">{fmt(data.profile.createdAt)}</dd>
              </dl>
            ) : (
              <div className="text-muted">{t.common.loading}</div>
            )}
          </Card>
        </div>

        {/* -------- update profile + change password -------- */}
        <div className="col-12 col-xl-8">
          <Card title={p.updateTitle} className="mb-4">
            <p className="text-muted ems-fs-13">{p.updateHint}</p>
            {message && (
              <div className="mb-3">
                <Alert type={message.type}>{message.text}</Alert>
              </div>
            )}
            <div className="row">
              <div className="col-md-6">
                <Input
                  label={t.common.name}
                  value={form.name}
                  onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                />
              </div>
              <div className="col-md-6">
                <Input
                  label={t.common.email}
                  type="email"
                  value={form.email}
                  onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
                />
              </div>
            </div>
            <Button loading={saving} onClick={saveProfile}>
              {p.updateBtn}
            </Button>
          </Card>

          <Card title={p.changeTitle}>
            {pwMessage && (
              <div className="mb-3">
                <Alert type={pwMessage.type}>{pwMessage.text}</Alert>
              </div>
            )}
            <div className="row">
              <div className="col-md-4">
                <Input
                  label={p.currentPassword}
                  type="password"
                  value={pw.currentPassword}
                  onChange={(e) => setPw((s) => ({ ...s, currentPassword: e.target.value }))}
                />
              </div>
              <div className="col-md-4">
                <Input
                  label={p.newPassword}
                  type="password"
                  value={pw.newPassword}
                  onChange={(e) => setPw((s) => ({ ...s, newPassword: e.target.value }))}
                />
              </div>
              <div className="col-md-4">
                <Input
                  label={p.confirmNewPassword}
                  type="password"
                  value={pw.confirmPassword}
                  onChange={(e) => setPw((s) => ({ ...s, confirmPassword: e.target.value }))}
                />
              </div>
            </div>
            <div className="d-flex align-items-center gap-3">
              <Button loading={pwSaving} onClick={changePassword}>
                {p.changeBtn}
              </Button>
              <span className="text-muted ems-fs-13">{p.passwordHint}</span>
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}
