"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  EmptyState,
  Modal,
  PageHeader,
  Pagination,
  Select,
  StatCard,
  StatusBadge,
  Textarea,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import {
  IconCheckCircle,
  IconClock,
  IconDownload,
  IconEye,
  IconLifeBuoy,
  IconPaperclip,
  IconSend,
} from "@/components/icons";

interface Ticket {
  id: number;
  subject: string;
  message: string;
  status: string;
  createdAt: string;
  updatedAt: string;
  replyCount: number;
  attachmentCount: number;
  lastReplyBy: string | null;
  lastActivityAt: string;
  institution: { id: number; name: string; type: string };
}

interface TicketMessage {
  id: number;
  senderRole: string;
  senderName: string;
  message: string;
  isSolution: boolean;
  createdAt: string;
}

interface TicketAttachment {
  id: number;
  fileName: string;
  mimeType: string;
  fileSize: number;
}

interface TicketDetail extends Omit<Ticket, "institution"> {
  institution: { id: number; name: string; type: string; email: string; phone: string };
  messages: TicketMessage[];
  attachments: TicketAttachment[];
}

const TICKET_STATUSES = ["OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"];

function fileKB(bytes: number): string {
  return bytes >= 1024 * 1024 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}

export default function CentralSupportPage() {
  const { t, locale } = useLang();
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [busy, setBusy] = useState(false);

  const [filterStatus, setFilterStatus] = useState("");
  const ticketsData = useApi<{ tickets: Ticket[] }>(
    filterStatus ? `/api/central/support?status=${filterStatus}` : "/api/central/support",
  );
  const tickets = ticketsData.data?.tickets ?? [];
  const count = (s: string) => tickets.filter((x) => x.status === s).length;
  const pager = usePagination(tickets, 10);

  // detail modal
  const [detailOpen, setDetailOpen] = useState(false);
  const [detail, setDetail] = useState<TicketDetail | null>(null);
  const [reply, setReply] = useState("");
  const [markSolution, setMarkSolution] = useState(false);

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

  async function openDetail(id: number) {
    try {
      const res = await fetch(`/api/central/support/${id}`, { credentials: "include" });
      if (!res.ok) throw new Error();
      const data = (await res.json()) as { ticket: TicketDetail };
      setDetail(data.ticket);
      setReply("");
      setMarkSolution(false);
      setDetailOpen(true);
    } catch {
      notify("error", t.common.tryAgain);
    }
  }

  async function reloadAll(id: number) {
    const res = await fetch(`/api/central/support/${id}`, { credentials: "include" });
    if (res.ok) {
      const data = (await res.json()) as { ticket: TicketDetail };
      setDetail(data.ticket);
    }
    ticketsData.reload();
  }

  async function sendUpdate() {
    if (!detail || !reply.trim()) return;
    setBusy(true);
    try {
      await api(`/api/central/support/${detail.id}/messages`, {
        method: "POST",
        body: JSON.stringify({ message: reply, isSolution: markSolution }),
      });
      setReply("");
      setMarkSolution(false);
      notify("success", markSolution ? t.central.supportPage.solutionSent : t.central.supportPage.updatePosted);
      await reloadAll(detail.id);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setBusy(false);
    }
  }

  async function changeStatus(status: string) {
    if (!detail) return;
    setBusy(true);
    try {
      await api(`/api/central/support/${detail.id}`, {
        method: "PATCH",
        body: JSON.stringify({ status }),
      });
      notify("success", t.central.supportPage.statusChanged);
      await reloadAll(detail.id);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setBusy(false);
    }
  }

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

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

      {/* Monitoring */}
      <div className="row g-3 mb-4">
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.central.supportPage.totalTickets} value={String(tickets.length)} icon={<IconLifeBuoy />} accent="teal" />
        </div>
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.status.OPEN} value={String(count("OPEN"))} icon={<IconLifeBuoy />} accent="orange" />
        </div>
        <div className="col-xl-2 col-sm-4 col-6">
          <StatCard label={t.status.IN_PROGRESS} value={String(count("IN_PROGRESS"))} icon={<IconClock />} accent="blue" />
        </div>
        <div className="col-xl-3 col-sm-4 col-6">
          <StatCard label={t.status.RESOLVED} value={String(count("RESOLVED"))} icon={<IconCheckCircle />} accent="purple" />
        </div>
        <div className="col-xl-3 col-sm-4 col-6">
          <StatCard label={t.status.CLOSED} value={String(count("CLOSED"))} icon={<IconCheckCircle />} accent="sky" />
        </div>
      </div>

      <div className="card">
        <div className="card-header">
          <div style={{ maxWidth: 240 }}>
            <Select wrapperClassName="form-group mb-0" value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)}>
              <option value="">{t.central.supportPage.allStatuses}</option>
              {TICKET_STATUSES.map((s) => (
                <option key={s} value={s}>{t.status[s as keyof typeof t.status]}</option>
              ))}
            </Select>
          </div>
        </div>

        {ticketsData.loading && !ticketsData.data ? (
          <div className="card-body text-center py-4">
            <span className="spinner-border text-primary" role="status" />
          </div>
        ) : tickets.length === 0 ? (
          <div className="card-body">
            <EmptyState icon={<IconLifeBuoy />} title={t.central.supportPage.noTickets} />
          </div>
        ) : (
          <>
            <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.central.supportPage.institution}</th>
                    <th>{t.central.supportPage.subjectLabel}</th>
                    <th>{t.common.status}</th>
                    <th className="text-center">{t.central.supportPage.replies}</th>
                    <th className="text-center">{t.central.supportPage.attachmentsLabel}</th>
                    <th>{t.central.supportPage.lastUpdate}</th>
                    <th className="text-end">{t.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {pager.paged.map((x) => (
                    <tr key={x.id}>
                      <td>
                        <p className="mb-0 f-w-700">{x.institution.name}</p>
                        <p className="mb-0 ems-fs-11 text-muted">{t.types[x.institution.type as keyof typeof t.types] ?? x.institution.type}</p>
                      </td>
                      <td>
                        <p className="mb-0 f-w-600">{x.subject}</p>
                        <p className="mb-0 ems-fs-11 text-muted">#{x.id} · {formatDate(x.createdAt, locale)}</p>
                      </td>
                      <td>
                        <StatusBadge status={x.status} label={t.status[x.status as keyof typeof t.status]} />
                      </td>
                      <td className="text-center f-w-600">{x.replyCount}</td>
                      <td className="text-center">
                        {x.attachmentCount > 0 ? (
                          <span className="badge badge-secondary">
                            <IconPaperclip className="svg-12" /> {x.attachmentCount}
                          </span>
                        ) : (
                          "—"
                        )}
                      </td>
                      <td className="ems-fs-12 text-muted">
                        {formatDate(x.lastActivityAt, locale)}
                        <p className="mb-0 ems-fs-11">
                          {x.lastReplyBy === "INSTITUTION_ADMIN"
                            ? t.central.supportPage.institution
                            : x.lastReplyBy === "SUPER_ADMIN"
                              ? t.central.supportPage.supportTeam
                              : ""}
                        </p>
                      </td>
                      <td className="text-end">
                        <Button size="sm" variant="secondary" title={t.central.supportPage.conversation} onClick={() => openDetail(x.id)}>
                          <IconEye className="svg-16" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination {...pager} onPageChange={pager.setPage} onSizeChange={pager.setSize} />
          </>
        )}
      </div>

      {/* Ticket detail modal */}
      <Modal
        open={detailOpen}
        onClose={() => setDetailOpen(false)}
        title={detail ? `#${detail.id} — ${detail.subject}` : ""}
        wide
      >
        {detail && (
          <div>
            <div className="d-flex flex-wrap align-items-center gap-2 mb-3">
              <StatusBadge status={detail.status} label={t.status[detail.status as keyof typeof t.status]} />
              <span className="ems-fs-12 text-muted">
                {detail.institution.name} · {t.central.supportPage.reportedOn} {formatDate(detail.createdAt, locale)}
              </span>
              <div className="ms-auto d-flex flex-wrap gap-1">
                {detail.status !== "IN_PROGRESS" && detail.status !== "CLOSED" && (
                  <Button size="sm" variant="secondary" disabled={busy} onClick={() => changeStatus("IN_PROGRESS")}>
                    {t.central.supportPage.startProgress}
                  </Button>
                )}
                {detail.status !== "RESOLVED" && detail.status !== "CLOSED" && (
                  <Button size="sm" variant="success" disabled={busy} onClick={() => changeStatus("RESOLVED")}>
                    {t.central.supportPage.resolve}
                  </Button>
                )}
                {detail.status !== "CLOSED" && (
                  <Button size="sm" variant="secondary" disabled={busy} onClick={() => changeStatus("CLOSED")}>
                    {t.central.supportPage.closeTicket}
                  </Button>
                )}
                {detail.status === "CLOSED" && (
                  <Button size="sm" variant="warning" disabled={busy} onClick={() => changeStatus("OPEN")}>
                    {t.central.supportPage.reopen}
                  </Button>
                )}
              </div>
            </div>

            <div className="ems-thread">
              {/* opening message — from the institution */}
              <div className="ems-thread-me ems-thread-item">
                <p className="mb-1 ems-fs-11 text-muted f-w-600">
                  {detail.institution.name} · {formatDate(detail.createdAt, locale)}
                </p>
                <p className="mb-0" style={{ whiteSpace: "pre-wrap" }}>{detail.message}</p>
              </div>
              {detail.messages.map((m) => (
                <div key={m.id} className={`ems-thread-item ${m.senderRole === "SUPER_ADMIN" ? "ems-thread-support" : "ems-thread-me"}`}>
                  <p className="mb-1 ems-fs-11 text-muted f-w-600">
                    {m.senderRole === "SUPER_ADMIN" ? `${t.central.supportPage.supportTeam} — ${m.senderName}` : detail.institution.name}
                    {" · "}
                    {formatDate(m.createdAt, locale)}
                    {m.isSolution && <span className="badge badge-success ms-2">{t.central.supportPage.solution}</span>}
                  </p>
                  <p className="mb-0" style={{ whiteSpace: "pre-wrap" }}>{m.message}</p>
                </div>
              ))}
            </div>

            {detail.attachments.length > 0 && (
              <div className="mt-3">
                <p className="mb-1 f-w-600 ems-fs-13">{t.central.supportPage.attachmentsLabel}</p>
                <div className="d-flex flex-wrap gap-2">
                  {detail.attachments.map((a) => (
                    <a
                      key={a.id}
                      href={`/api/attachment/${a.id}`}
                      target="_blank"
                      rel="noreferrer"
                      className="badge badge-secondary d-inline-flex align-items-center gap-1 text-decoration-none"
                    >
                      <IconDownload className="svg-12" />
                      {a.fileName} ({fileKB(a.fileSize)})
                    </a>
                  ))}
                </div>
              </div>
            )}

            <div className="mt-3 border-top pt-3">
              <Textarea
                label={t.central.supportPage.updateLabel}
                rows={2}
                value={reply}
                onChange={(e) => setReply(e.target.value)}
              />
              <div className="d-flex align-items-center justify-content-between">
                <div className="form-check">
                  <input
                    className="form-check-input"
                    type="checkbox"
                    id="markSolution"
                    checked={markSolution}
                    onChange={(e) => setMarkSolution(e.target.checked)}
                  />
                  <label className="form-check-label f-w-600 ems-fs-13" htmlFor="markSolution">
                    {t.central.supportPage.markSolution}
                  </label>
                </div>
                <Button loading={busy} disabled={!reply.trim()} onClick={sendUpdate}>
                  <IconSend className="svg-16" />
                  <span className="ms-1">{t.central.supportPage.postUpdate}</span>
                </Button>
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
