"use client";

import { useEffect, useRef, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import { Alert, Button, Card, Input, PageHeader, PageLoader, Select, StatusBadge, Textarea } from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { EDUCATION_BOARDS, TYPE_BADGE } from "@/lib/constants";
import { BD_DISTRICT_NAMES, subDistrictsOf } from "@/lib/bd-locations";
import { formatDate } from "@/lib/utils";
import { IconBuilding, IconEdit, IconLock, IconMail, IconShield } from "@/components/icons";

interface Profile {
  id: number;
  name: string;
  code: string;
  type: string;
  email: string;
  phone: string;
  address: string;
  district: string | null;
  subDistrict: string | null;
  eiin: string | null;
  ein: string | null;
  mpoCode: string | null;
  boardCode: string | null;
  educationBoard: string | null;
  establishedYear: number | null;
  postCode: string | null;
  logo: string | null;
  website: string | null;
  description: string | null;
  status: string;
  createdAt: string;
}

const emptyEdu = {
  eiin: "", ein: "", mpoCode: "", boardCode: "", educationBoard: "", establishedYear: "", postCode: "",
};

function eduFromProfile(p: Profile) {
  return {
    eiin: p.eiin ?? "",
    ein: p.ein ?? "",
    mpoCode: p.mpoCode ?? "",
    boardCode: p.boardCode ?? "",
    educationBoard: p.educationBoard ?? "",
    establishedYear: p.establishedYear ? String(p.establishedYear) : "",
    postCode: p.postCode ?? "",
  };
}

export default function PortalProfilePage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ institution: Profile }>("/api/portal/profile");
  // upload policy from the central credential
  const { data: uploadPolicy } = useApi<{ imageMaxKb: number; imageMaxDim: number; docMaxKb: number }>(
    "/api/portal/upload-policy"
  );
  const fileRef = useRef<HTMLInputElement>(null);

  const [form, setForm] = useState({
    name: "", phone: "", address: "", district: "", subDistrict: "", website: "", description: "",
  });
  const [edu, setEdu] = useState(emptyEdu);
  const [logo, setLogo] = useState<string | null>(null);
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // Change password (institution's own login credential)
  const [pwd, setPwd] = useState({ current: "", next: "", confirm: "" });
  const [pwdSaving, setPwdSaving] = useState(false);

  async function changePassword(e: React.FormEvent) {
    e.preventDefault();
    if (pwd.next.length < 6) {
      setMessage({ type: "error", text: t.common.minPassword });
      return;
    }
    if (pwd.next !== pwd.confirm) {
      setMessage({ type: "error", text: t.auth.passwordMismatch });
      return;
    }
    setPwdSaving(true);
    try {
      await api("/api/portal/profile/password", {
        method: "PUT",
        body: JSON.stringify({ currentPassword: pwd.current, newPassword: pwd.next }),
      });
      setPwd({ current: "", next: "", confirm: "" });
      setMessage({ type: "success", text: t.portal.profile.passwordChanged });
    } catch (err) {
      const text = err instanceof Error && err.message.includes("INVALID_PASSWORD")
        ? t.portal.profile.wrongPassword
        : t.common.tryAgain;
      setMessage({ type: "error", text });
    } finally {
      setPwdSaving(false);
    }
  }

  useEffect(() => {
    if (data?.institution) {
      const p = data.institution;
      setForm({
        name: p.name, phone: p.phone, address: p.address,
        district: p.district ?? "", subDistrict: p.subDistrict ?? "",
        website: p.website ?? "", description: p.description ?? "",
      });
      setEdu(eduFromProfile(p));
      setLogo(p.logo);
    }
  }, [data]);

  function handleLogoFile(file: File | undefined) {
    if (!file) return;
    if (file.size > (uploadPolicy?.imageMaxKb ?? 1024) * 1024) {
      setMessage({ type: "error", text: t.portal.profile.logoTooLarge });
      return;
    }
    const reader = new FileReader();
    reader.onload = () => {
      const url = String(reader.result);
      // Downscale via canvas (max 256px) so the stored data URL stays small;
      // fall back to the original data URL if the image can't be decoded.
      const img = new Image();
      img.onload = () => {
        const max = 256;
        const scale = Math.min(1, max / Math.max(img.width, img.height));
        const w = Math.max(1, Math.round(img.width * scale));
        const h = Math.max(1, Math.round(img.height * scale));
        const canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
        const ctx = canvas.getContext("2d");
        if (!ctx) {
          setLogo(url);
          return;
        }
        ctx.drawImage(img, 0, 0, w, h);
        const resized = canvas.toDataURL("image/png");
        setLogo(resized.length < url.length ? resized : url);
      };
      img.onerror = () => setLogo(url);
      img.src = url;
    };
    reader.readAsDataURL(file);
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      await api("/api/portal/profile", {
        method: "PUT",
        body: JSON.stringify({ ...form, ...edu, establishedYear: edu.establishedYear ? Number(edu.establishedYear) : null, logo }),
      });
      setMessage({ type: "success", text: t.portal.profile.profileUpdated });
      setEditing(false);
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <PageLoader text={t.common.loading} />;
  const p = data?.institution;
  if (!p) return null;

  return (
    <div>
      <PageHeader
        title={t.portal.profile.title}
        subtitle={t.portal.profile.subtitle}
        action={
          !editing ? (
            <Button onClick={() => setEditing(true)}>
              <IconEdit className="svg-16" />
              <span className="ms-1">{t.common.edit}</span>
            </Button>
          ) : undefined
        }
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      <div className="row g-4">
        {/* Profile card */}
        <div className="col-xl-4">
          <Card>
            <div className="text-center">
              {logo ? (
                <img
                  src={logo}
                  alt={p.name}
                  style={{ width: 110, height: 110, objectFit: "contain" }}
                  className="mb-3"
                />
              ) : (
                <span className="ems-stat-icon teal mb-3" style={{ width: 110, height: 110, borderRadius: "50%" }}>
                  <IconBuilding className="svg-32" />
                </span>
              )}
              <h4 className="f-w-800 mb-1">{p.name}</h4>
              <div className="d-flex justify-content-center gap-2 mb-3">
                <span className={`ems-type-pill ems-type-${p.type}`}>
                  {t.types[p.type as keyof typeof t.types]}
                </span>
                <StatusBadge status={p.status} label={t.status[p.status as keyof typeof t.status]} />
              </div>
              {/* Institution code — members use it to sign in */}
              <div className="mb-3">
                <p className="mb-1 ems-fs-11 text-muted">{t.auth.institutionCode}</p>
                <code
                  className="ems-invoice-badge cursor-pointer"
                  title={t.central.institutionsPage.copyCode}
                  onClick={() => {
                    navigator.clipboard?.writeText(p.code);
                    setMessage({ type: "success", text: t.common.copied });
                  }}
                >
                  {p.code}
                </code>
              </div>
              <hr />
              <div className="text-start">
                <p className="mb-2 d-flex align-items-center gap-2 ems-fs-13">
                  <IconMail className="svg-16 text-muted" /> {p.email}
                </p>
                <p className="mb-2 d-flex align-items-center gap-2 ems-fs-13">
                  <IconShield className="svg-16 text-muted" /> {p.phone}
                </p>
                <p className="mb-2 ems-fs-13 text-muted">{p.address}</p>
                {p.website && (
                  <p className="mb-2 ems-fs-13">
                    <a href={p.website} target="_blank" rel="noreferrer" className="ems-text-teal">
                      {p.website}
                    </a>
                  </p>
                )}
                <p className="mb-0 ems-fs-12 text-muted">
                  {t.portal.profile.memberSince}: {formatDate(p.createdAt, locale)}
                </p>
              </div>
            </div>
          </Card>
        </div>

        {/* Edit form */}
        <div className="col-xl-8">
          <Card title={t.portal.profile.title} icon={<IconBuilding className="svg-20" />}>
            {editing ? (
              <form className="theme-form" onSubmit={handleSave}>
                {/* Logo upload */}
                <div className="form-group mb-3">
                  <label className="col-form-label pt-0 f-w-600">{t.portal.profile.logo}</label>
                  <div className="d-flex align-items-center gap-3">
                    {logo ? (
                      <img src={logo} alt="logo" style={{ width: 64, height: 64, objectFit: "contain" }} />
                    ) : (
                      <span className="ems-stat-icon teal" style={{ width: 64, height: 64 }}>
                        <IconBuilding />
                      </span>
                    )}
                    <div className="d-flex flex-column gap-2">
                      <input
                        ref={fileRef}
                        type="file"
                        accept="image/png,image/jpeg"
                        className="d-none"
                        onChange={(e) => handleLogoFile(e.target.files?.[0])}
                      />
                      <Button type="button" variant="secondary" size="sm" onClick={() => fileRef.current?.click()}>
                        {logo ? t.portal.profile.changeLogo : t.portal.profile.uploadLogo}
                      </Button>
                      {logo && (
                        <Button type="button" variant="danger" size="sm" onClick={() => setLogo(null)}>
                          {t.portal.profile.removeLogo}
                        </Button>
                      )}
                    </div>
                  </div>
                  <p className="mb-0 ems-fs-11 text-muted mt-1">{t.portal.profile.logoHint}</p>
                </div>

                <div className="row">
                  <div className="col-md-6">
                    <Input
                      label={t.auth.institutionName}
                      required
                      value={form.name}
                      onChange={(e) => setForm({ ...form, name: e.target.value })}
                    />
                  </div>
                  <div className="col-md-6">
                    <Input
                      label={t.common.phone}
                      required
                      value={form.phone}
                      onChange={(e) => setForm({ ...form, phone: e.target.value })}
                    />
                  </div>
                  <div className="col-md-6">
                    <Select
                      label={t.common.district}
                      value={form.district}
                      onChange={(e) => setForm({ ...form, district: e.target.value, subDistrict: "" })}
                    >
                      <option value="">— {t.common.select} —</option>
                      {BD_DISTRICT_NAMES.map((d) => (
                        <option key={d} value={d}>
                          {d}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="col-md-6">
                    <Select
                      label={t.common.subDistrict}
                      value={form.subDistrict}
                      onChange={(e) => setForm({ ...form, subDistrict: e.target.value })}
                      disabled={!form.district}
                    >
                      <option value="">— {t.common.select} —</option>
                      {subDistrictsOf(form.district).map((s) => (
                        <option key={s} value={s}>
                          {s}
                        </option>
                      ))}
                    </Select>
                  </div>
                  <div className="col-md-12">
                    <Input
                      label={t.common.address}
                      required
                      value={form.address}
                      onChange={(e) => setForm({ ...form, address: e.target.value })}
                    />
                  </div>
                  <div className="col-md-12">
                    <Input
                      label={t.portal.profile.website}
                      value={form.website}
                      onChange={(e) => setForm({ ...form, website: e.target.value })}
                      placeholder="https://…"
                    />
                  </div>
                  <div className="col-md-12">
                    <Textarea
                      label={t.portal.profile.description}
                      value={form.description}
                      onChange={(e) => setForm({ ...form, description: e.target.value })}
                    />
                  </div>
                </div>

                {/* Bangladesh education-registry info */}
                <p className="f-w-700 ems-fs-13 mb-3 ems-text-teal">{t.portal.profile.sectionEduInfo}</p>
                <div className="row">
                  <div className="col-md-4">
                    <Input
                      label={t.common.eiin}
                      value={edu.eiin}
                      placeholder="108452"
                      onChange={(e) => setEdu({ ...edu, eiin: e.target.value })}
                    />
                  </div>
                  <div className="col-md-4">
                    <Input
                      label={t.common.ein}
                      value={edu.ein}
                      placeholder="53010540301"
                      onChange={(e) => setEdu({ ...edu, ein: e.target.value })}
                    />
                  </div>
                  <div className="col-md-4">
                    <Input
                      label={t.common.boardCode}
                      value={edu.boardCode}
                      placeholder="1015"
                      onChange={(e) => setEdu({ ...edu, boardCode: e.target.value })}
                    />
                  </div>
                  <div className="col-md-4">
                    <Select
                      label={t.common.educationBoard}
                      value={edu.educationBoard}
                      onChange={(e) => setEdu({ ...edu, educationBoard: e.target.value })}
                    >
                      <option value="">— {t.common.select} —</option>
                      {EDUCATION_BOARDS.map((b) => (
                        <option key={b} value={b}>{t.boards[b]}</option>
                      ))}
                    </Select>
                  </div>
                  <div className="col-md-4">
                    <Input
                      label={t.common.mpoCode}
                      value={edu.mpoCode}
                      onChange={(e) => setEdu({ ...edu, mpoCode: e.target.value })}
                    />
                  </div>
                  <div className="col-md-2">
                    <Input
                      label={t.common.establishedYear}
                      type="number"
                      value={edu.establishedYear}
                      placeholder="1985"
                      onChange={(e) => setEdu({ ...edu, establishedYear: e.target.value })}
                    />
                  </div>
                  <div className="col-md-2">
                    <Input
                      label={t.common.postCode}
                      value={edu.postCode}
                      placeholder="1205"
                      onChange={(e) => setEdu({ ...edu, postCode: e.target.value })}
                    />
                  </div>
                </div>
                <p className="ems-fs-11 text-muted">{t.portal.profile.eduInfoHint}</p>
                <div className="d-flex justify-content-end gap-2">
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={() => {
                      setEditing(false);
                      // restore
                      setForm({
                        name: p.name, phone: p.phone, address: p.address,
                        district: p.district ?? "", subDistrict: p.subDistrict ?? "",
                        website: p.website ?? "", description: p.description ?? "",
                      });
                      setEdu(eduFromProfile(p));
                      setLogo(p.logo);
                    }}
                  >
                    {t.common.cancel}
                  </Button>
                  <Button type="submit" loading={saving}>{t.common.saveChanges}</Button>
                </div>
              </form>
            ) : (
              <div>
                <dl className="row mb-0">
                  <dt className="col-sm-4 f-w-700">{t.auth.institutionName}</dt>
                  <dd className="col-sm-8">{p.name}</dd>
                  <dt className="col-sm-4 f-w-700">{t.common.email}</dt>
                  <dd className="col-sm-8">{p.email}</dd>
                  <dt className="col-sm-4 f-w-700">{t.common.phone}</dt>
                  <dd className="col-sm-8">{p.phone}</dd>
                  <dt className="col-sm-4 f-w-700">{t.common.address}</dt>
                  <dd className="col-sm-8">
                    {p.address}
                    {p.district && (
                      <span className="ms-1 text-muted">
                        ({p.district}
                        {p.subDistrict ? ` — ${p.subDistrict}` : ""})
                      </span>
                    )}
                  </dd>
                  <dt className="col-sm-4 f-w-700">{t.portal.profile.website}</dt>
                  <dd className="col-sm-8">{p.website ?? "—"}</dd>
                  <dt className="col-sm-4 f-w-700">{t.portal.profile.description}</dt>
                  <dd className="col-sm-8">{p.description ?? "—"}</dd>
                  <dt className="col-sm-4 f-w-700">{t.portal.profile.sectionEduInfo}</dt>
                  <dd className="col-sm-8">
                    {p.eiin || p.ein || p.boardCode || p.educationBoard || p.mpoCode || p.establishedYear || p.postCode ? (
                      <span className="ems-fs-13">
                        {[
                          p.eiin && `${t.common.eiin}: ${p.eiin}`,
                          p.ein && `${t.common.ein}: ${p.ein}`,
                          p.boardCode && `${t.common.boardCode}: ${p.boardCode}`,
                          p.educationBoard && `${t.common.educationBoard}: ${t.boards[p.educationBoard as keyof typeof t.boards] ?? p.educationBoard}`,
                          p.mpoCode && `${t.common.mpoCode}: ${p.mpoCode}`,
                          p.establishedYear && `${t.common.establishedYear}: ${p.establishedYear}`,
                          p.postCode && `${t.common.postCode}: ${p.postCode}`,
                        ].filter(Boolean).map((item, i) => (
                          <span key={i}>
                            {i > 0 && <span className="text-muted mx-1">·</span>}
                            {item}
                          </span>
                        ))}
                      </span>
                    ) : (
                      <span className="text-muted">—</span>
                    )}
                  </dd>
                </dl>
              </div>
            )}
          </Card>
        </div>
      </div>

      {/* Change password — the institution's own login credential */}
      <div className="row mt-4">
        <div className="col-12">
          <Card title={t.portal.profile.changePassword} icon={<IconLock className="svg-20" />}>
            <form className="theme-form" onSubmit={changePassword}>
              <div className="row">
                <div className="col-md-4">
                  <Input
                    label={t.portal.profile.currentPassword}
                    type="password"
                    required
                    value={pwd.current}
                    onChange={(e) => setPwd({ ...pwd, current: e.target.value })}
                  />
                </div>
                <div className="col-md-4">
                  <Input
                    label={t.portal.profile.newPassword}
                    type="password"
                    required
                    value={pwd.next}
                    onChange={(e) => setPwd({ ...pwd, next: e.target.value })}
                  />
                </div>
                <div className="col-md-4">
                  <Input
                    label={t.portal.profile.confirmNewPassword}
                    type="password"
                    required
                    value={pwd.confirm}
                    onChange={(e) => setPwd({ ...pwd, confirm: e.target.value })}
                  />
                </div>
              </div>
              <div className="d-flex justify-content-end">
                <Button type="submit" loading={pwdSaving} disabled={!pwd.current || pwd.next.length < 6 || !pwd.confirm}>
                  {t.portal.profile.changePassword}
                </Button>
              </div>
            </form>
          </Card>
        </div>
      </div>
    </div>
  );
}
