"use client";

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

interface LeaveRow {
  id: number;
  fromDate: string;
  toDate: string;
  days: number;
  reason: string;
  status: string;
  decidedAt: string | null;
  createdAt: string;
}

/** Teacher/staff leave self-service: apply for leave and track approvals. */
export default function MeLeavesPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ leaves: LeaveRow[] }>("/api/me/leaves");

  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ fromDate: "", toDate: "", reason: "" });
  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/leaves", {
        method: "POST",
        body: JSON.stringify(form),
      });
      setOpen(false);
      setForm({ fromDate: "", toDate: "", reason: "" });
      setMessage({ type: "success", text: t.me.leaveSubmitted });
      reload();
    } catch (err) {
      const code = err instanceof Error ? err.message : "";
      setMessage({
        type: "error",
        text: code === "MISSING_FIELDS" ? t.common.required : code === "INVALID_DATES" ? t.me.invalidDates : t.common.tryAgain,
      });
    } finally {
      setSaving(false);
    }
  }

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

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

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

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

      {leaves.length === 0 ? (
        <div className="card">
          <EmptyState icon={<IconCalendar />} title={t.me.noLeaves} />
        </div>
      ) : (
        <Card title={t.me.myLeaves} icon={<IconCalendar className="svg-20" />}>
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.me.fromCol}</th>
                  <th>{t.me.toCol}</th>
                  <th className="text-center">{t.common.days}</th>
                  <th>{t.common.reason}</th>
                  <th className="text-center">{t.common.status}</th>
                  <th>{t.me.decidedOn}</th>
                </tr>
              </thead>
              <tbody>
                {leaves.map((l) => (
                  <tr key={l.id}>
                    <td className="ems-fs-13">{formatDate(l.fromDate, locale)}</td>
                    <td className="ems-fs-13">{formatDate(l.toDate, locale)}</td>
                    <td className="text-center f-w-700">{l.days}</td>
                    <td className="ems-fs-13" style={{ maxWidth: 320 }}>{l.reason}</td>
                    <td className="text-center">
                      <StatusBadge status={l.status} label={t.status[l.status as keyof typeof t.status]} />
                    </td>
                    <td className="ems-fs-12 text-muted">
                      {l.decidedAt ? formatDate(l.decidedAt, locale) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      <Modal open={open} onClose={() => setOpen(false)} title={t.me.applyLeave}>
        <form className="theme-form" onSubmit={submit}>
          <div className="row">
            <div className="col-md-6">
              <DatePicker
                label={t.me.fromCol}
                value={form.fromDate}
                onChange={(e) => setForm({ ...form, fromDate: e.target.value })}
              />
            </div>
            <div className="col-md-6">
              <DatePicker
                label={t.me.toCol}
                value={form.toDate}
                min={form.fromDate || undefined}
                onChange={(e) => setForm({ ...form, toDate: e.target.value })}
              />
            </div>
          </div>
          <Textarea
            label={t.common.reason}
            required
            value={form.reason}
            onChange={(e) => setForm({ ...form, reason: 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.fromDate || !form.toDate || !form.reason.trim()}
            >
              {t.common.save}
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
