"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  DatePicker,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Select,
  StatCard,
  Textarea,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { EVENT_CATEGORIES } from "@/lib/constants";
import { IconCalendar, IconEdit, IconPlus, IconTrash } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface EventRow {
  id: number;
  title: string;
  titleBn: string | null;
  description: string | null;
  venue: string | null;
  category: string;
  startDate: string;
  endDate: string | null;
  isActive: boolean;
}

interface EventsData {
  stats: { total: number; upcoming: number; thisMonth: number; past: number };
  upcoming: EventRow[];
  past: EventRow[];
}

type Tab = "upcoming" | "past";

const emptyForm = {
  title: "",
  titleBn: "",
  description: "",
  venue: "",
  category: "ACADEMIC",
  startDate: "",
  endDate: "",
};

const ALL_NOTIFY_GROUPS = ["students", "parents", "teachers", "staff"];

export default function PortalEventsPage() {
  const { t, locale } = useLang();
  const [notifyGroups, setNotifyGroups] = useState<string[]>([...ALL_NOTIFY_GROUPS]);
  const [tab, setTab] = useState<Tab>("upcoming");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const { data, loading, reload } = useApi<EventsData>("/api/portal/events");

  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<EventRow | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);

  function notify(type: "success" | "error", text: string) {
    setMessage({ type, text });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function openCreate() {
    setEditing(null);
    setForm({ ...emptyForm, startDate: new Date().toISOString().slice(0, 10) });
    setFormOpen(true);
  }

  function openEdit(e: EventRow) {
    setEditing(e);
    setForm({
      title: e.title,
      titleBn: e.titleBn ?? "",
      description: e.description ?? "",
      venue: e.venue ?? "",
      category: EVENT_CATEGORIES.includes(e.category as never) ? e.category : "ACADEMIC",
      startDate: e.startDate,
      endDate: e.endDate ?? "",
    });
    setFormOpen(true);
  }

  async function save() {
    setSaving(true);
    try {
      if (editing) {
        await api(`/api/portal/events/${editing.id}`, { method: "PUT", body: JSON.stringify(form) });
        notify("success", t.portal.eventsPage.eventUpdated);
      } else {
        await api("/api/portal/events", { method: "POST", body: JSON.stringify({ ...form, notifyGroups }) });
        notify("success", t.portal.eventsPage.eventCreated);
      }
      setFormOpen(false);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setSaving(false);
    }
  }

  async function remove(e: EventRow) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/portal/events/${e.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;
  const list = tab === "upcoming" ? data?.upcoming ?? [] : data?.past ?? [];

  return (
    <div>
      <PageHeader
        title={t.portal.eventsPage.title}
        subtitle={t.portal.eventsPage.subtitle}
        action={
          <Button onClick={openCreate}>
            <IconPlus className="svg-16" />
            <span className="ms-1">{t.portal.eventsPage.newEvent}</span>
          </Button>
        }
      />

      {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-3 col-sm-6">
          <StatCard label={t.portal.eventsPage.totalEvents} value={String(s?.total ?? 0)} icon={<IconCalendar />} accent="teal" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.eventsPage.upcomingEvents} value={String(s?.upcoming ?? 0)} icon={<IconCalendar />} accent="sky" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.eventsPage.thisMonth} value={String(s?.thisMonth ?? 0)} icon={<IconCalendar />} accent="purple" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.eventsPage.pastEvents} value={String(s?.past ?? 0)} icon={<IconCalendar />} accent="orange" />
        </div>
      </div>

      <ul className="nav nav-tabs mb-4" role="tablist">
        {(["upcoming", "past"] as Tab[]).map((key) => {
          const labels: Record<Tab, string> = {
            upcoming: t.portal.eventsPage.tabUpcoming,
            past: t.portal.eventsPage.tabPast,
          };
          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.length === 0 ? (
        <div className="card">
          <EmptyState
            icon={<IconCalendar />}
            title={tab === "upcoming" ? t.portal.eventsPage.noUpcoming : t.portal.eventsPage.noPast}
            action={
              tab === "upcoming" ? (
                <Button onClick={openCreate}>
                  <IconPlus className="svg-16" />
                  <span className="ms-1">{t.portal.eventsPage.newEvent}</span>
                </Button>
              ) : undefined
            }
          />
        </div>
      ) : (
        <div className="row g-3">
          {list.map((e) => (
            <div className="col-xl-6" key={e.id}>
              <Card>
                <div className="d-flex justify-content-between align-items-start gap-2">
                  <div className="min-w-0">
                    <h5 className="f-w-700 mb-1">{e.title}</h5>
                    <p className="mb-1 ems-fs-12 text-muted">
                      {formatDate(e.startDate, locale)}
                      {e.endDate ? ` — ${formatDate(e.endDate, locale)}` : ""}
                      {e.venue ? ` · ${e.venue}` : ""}
                      {!e.isActive ? ` · ${t.common.inactive}` : ""}
                    </p>
                    {e.description && <p className="mb-2 ems-fs-13">{e.description}</p>}
                    <span className="ems-type-pill">
                      {t.eventCategories[e.category as keyof typeof t.eventCategories] ?? e.category}
                    </span>
                  </div>
                  <div className="d-flex flex-shrink-0">
                    <button className="btn btn-soft-secondary btn-sm me-1" onClick={() => openEdit(e)} type="button">
                      <IconEdit className="svg-16" />
                    </button>
                    <button className="btn btn-soft-danger btn-sm" onClick={() => remove(e)} type="button">
                      <IconTrash className="svg-16" />
                    </button>
                  </div>
                </div>
              </Card>
            </div>
          ))}
        </div>
      )}

      {/* Create/edit modal */}
      <Modal
        open={formOpen}
        onClose={() => setFormOpen(false)}
        title={editing ? t.portal.eventsPage.editEvent : t.portal.eventsPage.newEvent}
        wide
      >
        <div className="row">
          <div className="col-md-6">
            <Input label={t.portal.eventsPage.eventTitle} value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
          </div>
          <div className="col-md-6">
            <Input label={t.portal.eventsPage.eventTitleBn} value={form.titleBn} onChange={(e) => setForm({ ...form, titleBn: e.target.value })} />
          </div>
          <div className="col-md-4">
            <Select label={t.common.category} value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
              {EVENT_CATEGORIES.map((c) => (
                <option key={c} value={c}>
                  {t.eventCategories[c]}
                </option>
              ))}
            </Select>
          </div>
          <div className="col-md-8">
            <Input label={t.portal.eventsPage.venue} value={form.venue} onChange={(e) => setForm({ ...form, venue: e.target.value })} placeholder="Auditorium / Playground" />
          </div>
          <div className="col-md-6">
            <DatePicker label={t.portal.eventsPage.startDate} value={form.startDate} onChange={(e) => setForm({ ...form, startDate: e.target.value })} />
          <div className="col-md-12">
            <label className="col-form-label pt-0 f-w-600">{t.notifications.pushTo}</label>
            <div className="d-flex flex-wrap gap-3">
              {[["students", t.notifications.groupStudents], ["parents", t.notifications.groupParents], ["teachers", t.notifications.groupTeachers], ["staff", t.notifications.groupStaff]].map(([key, label]) => (
                <div className="form-check" key={key}>
                  <input
                    className="form-check-input"
                    type="checkbox"
                    id={`event-notify-${key}`}
                    checked={notifyGroups.includes(key)}
                    onChange={(e) =>
                      setNotifyGroups((prev) =>
                        e.target.checked ? [...prev, key] : prev.filter((g) => g !== key)
                      )
                    }
                  />
                  <label className="form-check-label ems-fs-13" htmlFor={`event-notify-${key}`}>
                    {label}
                  </label>
                </div>
              ))}
            </div>
          </div>
          </div>
          <div className="col-md-6">
            <DatePicker label={`${t.portal.eventsPage.endDate} (${t.common.optional})`} value={form.endDate} onChange={(e) => setForm({ ...form, endDate: e.target.value })} />
          </div>
          <div className="col-md-12">
            <Textarea label={t.portal.eventsPage.description} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </div>
        </div>
        <div className="d-flex justify-content-end gap-2">
          <Button variant="secondary" onClick={() => setFormOpen(false)}>
            {t.common.cancel}
          </Button>
          <Button onClick={save} loading={saving} disabled={!form.title.trim() || !form.startDate}>
            {t.common.save}
          </Button>
        </div>
      </Modal>
    </div>
  );
}
