"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  LoadingArea,
  Select,
  StatusBadge,
  Textarea,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { COMPLAINT_CATEGORIES } from "@/lib/constants";
import { IconAlertTriangle, IconPlus } from "@/components/icons";

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

const emptyForm = { category: "GENERAL", subject: "", description: "" };

/** Student/parent: submit complaints to the institution and track their status. */
export default function MeComplaintsPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ complaints: ComplaintRow[] }>("/api/me/complaints");

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

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      await api("/api/me/complaints", {
        method: "POST",
        body: JSON.stringify(form),
      });
      setOpen(false);
      setForm(emptyForm);
      setMessage({ type: "success", text: t.me.complaintSubmitted });
      reload();
    } catch (err) {
      const code = err instanceof Error ? err.message : "";
      setMessage({
        type: "error",
        text: code === "MISSING_FIELDS" ? t.common.required : t.common.tryAgain,
      });
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <div>
        <PageHeader
          title={t.me.complaintsTitle}
          subtitle={t.me.complaintsSubtitle}
          action={
            <Button onClick={() => setOpen(true)}>
              <IconPlus className="svg-16" />
              <span className="ms-1">{t.me.newComplaint}</span>
            </Button>
          }
        />
        <LoadingArea label={t.common.loading} />
      </div>
    );
  }

  const complaints = data?.complaints ?? [];

  return (
    <div>
      <PageHeader
        title={t.me.complaintsTitle}
        subtitle={t.me.complaintsSubtitle}
        action={
          <Button onClick={() => setOpen(true)}>
            <IconPlus className="svg-16" />
            <span className="ms-1">{t.me.newComplaint}</span>
          </Button>
        }
      />

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

      {complaints.length === 0 ? (
        <div className="card">
          <EmptyState icon={<IconAlertTriangle />} title={t.me.noComplaints} />
        </div>
      ) : (
        <Card title={t.me.myComplaints} icon={<IconAlertTriangle className="svg-20" />}>
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.common.subject}</th>
                  <th>{t.common.category}</th>
                  <th>{t.common.createdAt}</th>
                  <th className="text-center">{t.common.status}</th>
                  <th>{t.me.responseCol}</th>
                </tr>
              </thead>
              <tbody>
                {complaints.map((c) => (
                  <tr key={c.id}>
                    <td className="f-w-600 ems-fs-13">
                      {c.subject}
                      <span className="d-block ems-fs-11 text-muted" style={{ maxWidth: 360 }}>
                        {c.description}
                      </span>
                    </td>
                    <td className="ems-fs-12">
                      {t.complaintCategories[c.category as keyof typeof t.complaintCategories] ?? c.category}
                    </td>
                    <td className="ems-fs-12 text-muted">{formatDate(c.createdAt, locale)}</td>
                    <td className="text-center">
                      <StatusBadge status={c.status} label={t.status[c.status as keyof typeof t.status]} />
                    </td>
                    <td className="ems-fs-12">
                      {c.responseNote ? (
                        <span className="text-success">{c.responseNote}</span>
                      ) : (
                        <span className="text-muted">—</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      <Modal open={open} onClose={() => setOpen(false)} title={t.me.newComplaint}>
        <form className="theme-form" onSubmit={submit}>
          <Select
            label={t.common.category}
            value={form.category}
            onChange={(e) => setForm({ ...form, category: e.target.value })}
          >
            {COMPLAINT_CATEGORIES.map((c) => (
              <option key={c} value={c}>
                {t.complaintCategories[c as keyof typeof t.complaintCategories] ?? c}
              </option>
            ))}
          </Select>
          <Input
            label={t.common.subject}
            required
            value={form.subject}
            onChange={(e) => setForm({ ...form, subject: e.target.value })}
          />
          <Textarea
            label={t.me.complaintDetails}
            required
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
          />
          <div className="d-flex justify-content-end gap-2">
            <Button type="button" variant="secondary" onClick={() => setOpen(false)}>
              {t.common.cancel}
            </Button>
            <Button type="submit" loading={saving} disabled={!form.subject.trim() || !form.description.trim()}>
              {t.common.save}
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
