"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  StatCard,
  StatusBadge,
  Textarea,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { COMPLAINT_CATEGORIES, COMPLAINT_STATUSES, COMPLAINT_TYPES } from "@/lib/constants";
import { emsConfirm } from "@/components/ConfirmDialog";
import {
  IconCheck,
  IconEdit,
  IconMessageCircle,
  IconPlus,
  IconTrash,
} from "@/components/icons";

interface ComplaintRow {
  id: number;
  complainantType: string;
  complainantName: string;
  studentRef: string | null;
  category: string;
  subject: string;
  description: string;
  status: string;
  responseNote: string | null;
  resolvedAt: string | null;
  createdAt: string;
}

interface ComplaintsData {
  stats: { total: number; pending: number; inReview: number; resolved: number; rejected: number };
  complaints: ComplaintRow[];
}

interface StudentMini {
  id: number;
  roll: string;
  name: string;
}

type Tab = "file" | "list";
type Filter = "ALL" | "PENDING" | "IN_REVIEW" | "RESOLVED" | "REJECTED";

const emptyForm = {
  complainantType: "STUDENT",
  complainantName: "",
  studentId: "",
  category: "GENERAL",
  subject: "",
  description: "",
};

export default function PortalComplaintsPage() {
  const { t, locale } = useLang();
  const [tab, setTab] = useState<Tab>("list");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const { data, loading, reload } = useApi<ComplaintsData>("/api/portal/complaints");
  const { data: studentsData } = useApi<{ students: StudentMini[] }>("/api/portal/students");

  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [filter, setFilter] = useState<Filter>("ALL");

  const [responding, setResponding] = useState<ComplaintRow | null>(null);
  const [response, setResponse] = useState({ status: "IN_REVIEW", note: "" });
  const [respondSaving, setRespondSaving] = useState(false);

  const complaints = useMemo(() => {
    if (!data) return [];
    return filter === "ALL" ? data.complaints : data.complaints.filter((c) => c.status === filter);
  }, [data, filter]);

  const complaintsPager = usePagination(complaints, 10);

  function notify(type: "success" | "error", text: string) {
    setMessage({ type, text });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function file() {
    setSaving(true);
    try {
      await api("/api/portal/complaints", { method: "POST", body: JSON.stringify(form) });
      setForm(emptyForm);
      reload();
      setTab("list");
      notify("success", t.portal.complaintsPage.complaintFiled);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setSaving(false);
    }
  }

  function openRespond(c: ComplaintRow) {
    setResponding(c);
    setResponse({ status: c.status === "PENDING" ? "IN_REVIEW" : c.status, note: c.responseNote ?? "" });
  }

  async function saveResponse() {
    if (!responding) return;
    setRespondSaving(true);
    try {
      await api(`/api/portal/complaints/${responding.id}`, {
        method: "PUT",
        body: JSON.stringify({ status: response.status, responseNote: response.note }),
      });
      setResponding(null);
      reload();
      notify("success", t.portal.complaintsPage.complaintUpdated);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setRespondSaving(false);
    }
  }

  async function remove(c: ComplaintRow) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/portal/complaints/${c.id}`, { method: "DELETE" });
      notify("success", t.common.deletedSuccessfully);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    }
  }

  if (loading) return <PageLoader text={t.common.loading} />;
  const s = data?.stats;

  return (
    <div>
      <PageHeader title={t.portal.complaintsPage.title} subtitle={t.portal.complaintsPage.subtitle} />

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

      <div className="row g-3 mb-4">
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.portal.complaintsPage.totalLabel} value={String(s?.total ?? 0)} icon={<IconMessageCircle />} accent="teal" />
        </div>
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.status.PENDING} value={String(s?.pending ?? 0)} icon={<IconMessageCircle />} accent="orange" />
        </div>
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.status.IN_REVIEW} value={String(s?.inReview ?? 0)} icon={<IconEdit />} accent="sky" />
        </div>
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.status.RESOLVED} value={String(s?.resolved ?? 0)} icon={<IconCheck />} accent="purple" />
        </div>
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.status.REJECTED} value={String(s?.rejected ?? 0)} icon={<IconTrash />} accent="red" />
        </div>
      </div>

      <ul className="nav nav-tabs mb-4" role="tablist">
        {(["list", "file"] as Tab[]).map((key) => {
          const labels: Record<Tab, string> = {
            list: t.portal.complaintsPage.tabList,
            file: t.portal.complaintsPage.tabFile,
          };
          return (
            <li className="nav-item" key={key}>
              <button className={`nav-link ${tab === key ? "active" : ""}`} onClick={() => setTab(key)} type="button">
                {labels[key]}
              </button>
            </li>
          );
        })}
      </ul>

      {/* ---------- List tab ---------- */}
      {tab === "list" && (
        <div className="card">
          <div className="card-header d-flex flex-wrap align-items-center gap-2">
            {(["ALL", "PENDING", "IN_REVIEW", "RESOLVED", "REJECTED"] as Filter[]).map((f) => (
              <button
                key={f}
                type="button"
                className={`btn btn-sm ${filter === f ? "btn-primary" : "btn-soft-secondary"}`}
                onClick={() => setFilter(f)}
              >
                {f === "ALL" ? t.common.all : t.status[f]}
              </button>
            ))}
          </div>
          {complaints.length === 0 ? (
            <EmptyState icon={<IconMessageCircle />} title={t.portal.complaintsPage.noComplaints} />
          ) : (
            <>
              <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.portal.complaintsPage.complainant}</th>
                    <th>{t.portal.complaintsPage.subjectLabel}</th>
                    <th>{t.common.category}</th>
                    <th>{t.common.date}</th>
                    <th>{t.common.status}</th>
                    <th className="text-end">{t.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {complaintsPager.paged.map((c) => (
                    <tr key={c.id}>
                      <td>
                        <p className="mb-0 f-w-700">{c.complainantName}</p>
                        <p className="mb-0 ems-fs-11 text-muted">
                          {t.complaintTypes[c.complainantType as keyof typeof t.complaintTypes] ?? c.complainantType}
                          {c.studentRef ? ` · ${c.studentRef}` : ""}
                        </p>
                      </td>
                      <td style={{ maxWidth: 320 }}>
                        <p className="mb-0 f-w-600">{c.subject}</p>
                        <p className="mb-0 ems-fs-11 text-muted text-truncate">{c.description}</p>
                      </td>
                      <td>
                        <span className="ems-type-pill">
                          {t.complaintCategories[c.category as keyof typeof t.complaintCategories] ?? c.category}
                        </span>
                      </td>
                      <td className="ems-fs-13">{formatDate(c.createdAt, locale)}</td>
                      <td>
                        <StatusBadge status={c.status} label={t.status[c.status as keyof typeof t.status]} />
                      </td>
                      <td className="text-end">
                        <button className="btn btn-soft-primary btn-sm me-1" onClick={() => openRespond(c)} type="button">
                          <IconEdit className="svg-16" />
                        </button>
                        <button className="btn btn-soft-danger btn-sm" onClick={() => remove(c)} type="button">
                          <IconTrash className="svg-16" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              </div>
              <Pagination {...complaintsPager} onPageChange={complaintsPager.setPage} onSizeChange={complaintsPager.setSize} />
            </>
          )}
        </div>
      )}

      {/* ---------- File tab ---------- */}
      {tab === "file" && (
        <div className="row">
          <div className="col-xl-7">
            <Card title={t.portal.complaintsPage.tabFile} icon={<IconMessageCircle className="svg-18" />}>
              <Select
                label={t.portal.complaintsPage.complainantType}
                value={form.complainantType}
                onChange={(e) => setForm({ ...form, complainantType: e.target.value, studentId: "" })}
              >
                {COMPLAINT_TYPES.map((ct) => (
                  <option key={ct} value={ct}>
                    {t.complaintTypes[ct]}
                  </option>
                ))}
              </Select>
              {form.complainantType === "STUDENT" && (
                <Select
                  label={t.portal.complaintsPage.linkedStudent}
                  value={form.studentId}
                  onChange={(e) => setForm({ ...form, studentId: e.target.value })}
                >
                  <option value="">— {t.common.filter} —</option>
                  {(studentsData?.students ?? []).map((st) => (
                    <option key={st.id} value={st.id}>
                      {st.roll} — {st.name}
                    </option>
                  ))}
                </Select>
              )}
              <Input
                label={t.portal.complaintsPage.complainantName}
                value={form.complainantName}
                onChange={(e) => setForm({ ...form, complainantName: e.target.value })}
              />
              <Select label={t.common.category} value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
                {COMPLAINT_CATEGORIES.map((cat) => (
                  <option key={cat} value={cat}>
                    {t.complaintCategories[cat]}
                  </option>
                ))}
              </Select>
              <Input label={t.portal.complaintsPage.subjectLabel} value={form.subject} onChange={(e) => setForm({ ...form, subject: e.target.value })} />
              <Textarea
                label={t.portal.complaintsPage.descriptionLabel}
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
              />
              <Button
                onClick={file}
                loading={saving}
                disabled={!form.complainantName.trim() || !form.subject.trim() || !form.description.trim()}
              >
                <IconPlus className="svg-16" />
                <span className="ms-1">{t.portal.complaintsPage.submitComplaint}</span>
              </Button>
            </Card>
          </div>
        </div>
      )}

      {/* Respond modal */}
      <Modal
        open={!!responding}
        onClose={() => setResponding(null)}
        title={t.portal.complaintsPage.respondTitle}
        wide
      >
        {responding && (
          <>
            <div className="mb-3">
              <h6 className="f-w-700 mb-1">{responding.subject}</h6>
              <p className="mb-2 ems-fs-13" style={{ whiteSpace: "pre-wrap" }}>{responding.description}</p>
              <p className="mb-0 ems-fs-12 text-muted">
                {responding.complainantName} · {formatDate(responding.createdAt, locale)}
              </p>
            </div>
            <Select
              label={t.common.status}
              value={response.status}
              onChange={(e) => setResponse({ ...response, status: e.target.value })}
            >
              {COMPLAINT_STATUSES.map((st) => (
                <option key={st} value={st}>
                  {t.status[st]}
                </option>
              ))}
            </Select>
            <Textarea
              label={t.portal.complaintsPage.responseNote}
              value={response.note}
              onChange={(e) => setResponse({ ...response, note: e.target.value })}
            />
            <div className="d-flex justify-content-end gap-2">
              <Button variant="secondary" onClick={() => setResponding(null)}>
                {t.common.cancel}
              </Button>
              <Button onClick={saveResponse} loading={respondSaving} disabled={!response.status}>
                {t.common.saveChanges}
              </Button>
            </div>
          </>
        )}
      </Modal>
    </div>
  );
}
