"use client";

import { useState, useEffect, useMemo } from "react";
import { Loader2, Trash2, Phone, Instagram, Send, ChevronDown, ChevronRight, Bell, CheckCircle2, XCircle, Clock, Star, Calendar, DoorOpen } from "lucide-react";
import { adminFetch } from "@/lib/csrf";

// --- Types ---

interface GroupBooking {
  id: number;
  name: string;
  phone: string;
  groupInfo?: string;
  instagram?: string;
  telegram?: string;
  notifiedConfirm: boolean;
  notifiedReminder: boolean;
  createdAt: string;
}

interface McRegistration {
  id: number;
  masterClassTitle: string;
  name: string;
  phone?: string;
  instagram: string;
  telegram?: string;
  notifiedConfirm: boolean;
  notifiedReminder: boolean;
  createdAt: string;
}

interface OpenDayBooking {
  id: number;
  classId: number;
  eventId: number;
  name: string;
  phone: string;
  instagram?: string;
  telegram?: string;
  notifiedConfirm: boolean;
  notifiedReminder: boolean;
  createdAt: string;
  classStyle?: string;
  classTrainer?: string;
  classTime?: string;
  classHall?: string;
}

type Tab = "reminders" | "classes" | "master-classes" | "open-day";

// --- Group Bookings Tab ---

function GroupBookingsTab() {
  const [bookings, setBookings] = useState<GroupBooking[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminFetch("/api/admin/group-bookings")
      .then((r) => r.json())
      .then((data: GroupBooking[]) => setBookings(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function handleDelete(id: number) {
    await adminFetch(`/api/admin/group-bookings?id=${id}`, { method: "DELETE" });
    setBookings((prev) => prev.filter((b) => b.id !== id));
  }

  if (loading) return <LoadingSpinner />;

  return (
    <div className="space-y-2">
      {bookings.length === 0 && <EmptyState total={0} />}
      {bookings.map((b) => (
        <div
          key={b.id}
          className="rounded-xl border border-white/10 bg-neutral-900 p-4"
        >
            <div className="flex items-start justify-between gap-3">
              <div className="flex items-center gap-2 flex-wrap text-sm min-w-0">
                <span className="font-medium text-white">{b.name}</span>
                <a href={`tel:${b.phone.replace(/\D/g, "")}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
                  <Phone size={10} />{b.phone}
                </a>
                {b.instagram && (
                  <a href={`https://ig.me/m/${b.instagram.replace(/^@/, "")}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-pink-400 hover:text-pink-300 text-xs">
                    <Instagram size={10} />{b.instagram}
                  </a>
                )}
                {b.telegram && (
                  <a href={`https://t.me/${b.telegram.replace(/^@/, "")}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-blue-400 hover:text-blue-300 text-xs">
                    <Send size={10} />{b.telegram}
                  </a>
                )}
                {b.groupInfo && (
                  <span className="text-xs text-neutral-400 bg-neutral-800 rounded-full px-2 py-0.5">{b.groupInfo}</span>
                )}
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <span className="text-neutral-600 text-xs">{fmtDate(b.createdAt)}</span>
                <DeleteBtn onClick={() => handleDelete(b.id)} />
              </div>
            </div>
          </div>
        ))}
    </div>
  );
}

// --- MC Registrations Tab ---

function McRegistrationsTab() {
  const [regs, setRegs] = useState<McRegistration[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminFetch("/api/admin/mc-registrations")
      .then((r) => r.json())
      .then((data: McRegistration[]) => setRegs(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  // Group by MC title
  const grouped = useMemo(() => {
    const map: Record<string, McRegistration[]> = {};
    for (const r of regs) {
      if (!map[r.masterClassTitle]) map[r.masterClassTitle] = [];
      map[r.masterClassTitle].push(r);
    }
    return map;
  }, [regs]);

  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  function toggleExpand(key: string) {
    setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
  }

  async function handleDelete(id: number) {
    await adminFetch(`/api/admin/mc-registrations?id=${id}`, { method: "DELETE" });
    setRegs((prev) => prev.filter((r) => r.id !== id));
  }

  if (loading) return <LoadingSpinner />;

  return (
    <div className="space-y-2">
      {Object.keys(grouped).length === 0 && <EmptyState total={regs.length} />}
      {Object.entries(grouped).map(([title, items]) => {
        const isOpen = expanded[title] ?? false;
        return (
          <div key={title} className="rounded-xl border border-white/10 overflow-hidden">
            <button
              onClick={() => toggleExpand(title)}
              className="w-full flex items-center gap-3 px-4 py-3 bg-neutral-900 hover:bg-neutral-800/80 transition-colors text-left"
            >
              {isOpen ? <ChevronDown size={14} className="text-neutral-500 shrink-0" /> : <ChevronRight size={14} className="text-neutral-500 shrink-0" />}
              <span className="font-medium text-white text-sm truncate">{title}</span>
              <span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">{items.length}</span>
            </button>
            {isOpen && (
              <div className="px-4 pb-3 pt-1 space-y-1.5">
                {items.map((r) => (
                  <div
                    key={r.id}
                    className="rounded-lg border border-white/5 bg-neutral-800/30 p-3"
                  >
                      <div className="flex items-center gap-2 flex-wrap text-sm">
                        <span className="font-medium text-white">{r.name}</span>
                        {r.phone && (
                          <a href={`tel:${r.phone.replace(/\D/g, "")}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
                            <Phone size={10} />{r.phone}
                          </a>
                        )}
                        {r.instagram && (
                          <a
                            href={`https://ig.me/m/${r.instagram.replace(/^@/, "")}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-pink-400 hover:text-pink-300 text-xs"
                          >
                            <Instagram size={10} />{r.instagram}
                          </a>
                        )}
                        {r.telegram && (
                          <a
                            href={`https://t.me/${r.telegram.replace(/^@/, "")}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-blue-400 hover:text-blue-300 text-xs"
                          >
                            <Send size={10} />{r.telegram}
                          </a>
                        )}
                        <span className="text-neutral-600 text-xs ml-auto">{fmtDate(r.createdAt)}</span>
                        <DeleteBtn onClick={() => handleDelete(r.id)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
    </div>
  );
}

// --- Open Day Bookings Tab ---

function OpenDayBookingsTab() {
  const [bookings, setBookings] = useState<OpenDayBooking[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminFetch("/api/admin/open-day")
      .then((r) => r.json())
      .then((events: { id: number; date: string }[]) => {
        if (events.length === 0) {
          setLoading(false);
          return;
        }
        const ev = events[0];
        return adminFetch(`/api/admin/open-day/bookings?eventId=${ev.id}`)
          .then((r) => r.json())
          .then((data: OpenDayBooking[]) => setBookings(data));
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  // Group by class — sorted by hall then time
  const grouped = useMemo(() => {
    const map: Record<string, { hall: string; time: string; style: string; trainer: string; items: OpenDayBooking[] }> = {};
    for (const b of bookings) {
      const key = `${b.classHall}|${b.classTime}|${b.classStyle}`;
      if (!map[key]) map[key] = { hall: b.classHall || "—", time: b.classTime || "—", style: b.classStyle || "—", trainer: b.classTrainer || "—", items: [] };
      map[key].items.push(b);
    }
    // Sort by hall, then time
    return Object.entries(map).sort(([, a], [, b]) => {
      const hallCmp = a.hall.localeCompare(b.hall);
      return hallCmp !== 0 ? hallCmp : a.time.localeCompare(b.time);
    });
  }, [bookings]);

  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  function toggleExpand(key: string) {
    setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
  }

  async function handleDelete(id: number) {
    await adminFetch(`/api/admin/open-day/bookings?id=${id}`, { method: "DELETE" });
    setBookings((prev) => prev.filter((b) => b.id !== id));
  }

  if (loading) return <LoadingSpinner />;

  return (
    <div className="space-y-2">
      {grouped.length === 0 && <EmptyState total={bookings.length} />}
      {grouped.map(([key, group]) => {
        const isOpen = expanded[key] ?? false;
        return (
          <div key={key} className="rounded-xl border border-white/10 overflow-hidden">
            <button
              onClick={() => toggleExpand(key)}
              className="w-full flex items-center gap-3 px-4 py-3 bg-neutral-900 hover:bg-neutral-800/80 transition-colors text-left"
            >
              {isOpen ? <ChevronDown size={14} className="text-neutral-500 shrink-0" /> : <ChevronRight size={14} className="text-neutral-500 shrink-0" />}
              <span className="text-gold text-xs font-medium shrink-0">{group.time}</span>
              <span className="font-medium text-white text-sm truncate">{group.style}</span>
              <span className="text-xs text-neutral-500 truncate hidden sm:inline">· {group.trainer}</span>
              <span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0 ml-auto">{group.hall}</span>
              <span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5 shrink-0">{group.items.length} чел.</span>
            </button>
            {isOpen && (
              <div className="px-4 pb-3 pt-1 space-y-1.5">
                {group.items.map((b) => (
                  <div
                    key={b.id}
                    className="rounded-lg border border-white/5 bg-neutral-800/30 p-3"
                  >
                      <div className="flex items-center gap-2 flex-wrap text-sm">
                        <span className="font-medium text-white">{b.name}</span>
                        <a href={`tel:${b.phone}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
                          <Phone size={10} />{b.phone}
                        </a>
                        {b.instagram && (
                          <a
                            href={`https://ig.me/m/${b.instagram.replace(/^@/, "")}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-pink-400 hover:text-pink-300 text-xs"
                          >
                            <Instagram size={10} />{b.instagram}
                          </a>
                        )}
                        {b.telegram && (
                          <a
                            href={`https://t.me/${b.telegram.replace(/^@/, "")}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center gap-1 text-blue-400 hover:text-blue-300 text-xs"
                          >
                            <Send size={10} />{b.telegram}
                          </a>
                        )}
                        <span className="text-neutral-600 text-xs ml-auto">{fmtDate(b.createdAt)}</span>
                        <DeleteBtn onClick={() => handleDelete(b.id)} />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
    </div>
  );
}

// --- Reminders Tab ---

interface ReminderItem {
  id: number;
  type: "class" | "master-class" | "open-day";
  table: "mc_registrations" | "group_bookings" | "open_day_bookings";
  name: string;
  phone?: string;
  instagram?: string;
  telegram?: string;
  reminderStatus?: string;
  eventLabel: string;
  eventDate: string;
}

type ReminderStatus = "pending" | "coming" | "cancelled";

const STATUS_CONFIG: Record<ReminderStatus, { label: string; icon: typeof CheckCircle2; color: string; bg: string; border: string }> = {
  pending: { label: "Нет ответа", icon: Clock, color: "text-amber-400", bg: "bg-amber-500/10", border: "border-amber-500/20" },
  coming: { label: "Придёт", icon: CheckCircle2, color: "text-emerald-400", bg: "bg-emerald-500/10", border: "border-emerald-500/20" },
  cancelled: { label: "Не придёт", icon: XCircle, color: "text-red-400", bg: "bg-red-500/10", border: "border-red-500/20" },
};

const TYPE_CONFIG = {
  "master-class": { label: "МК", icon: Star, color: "text-purple-400" },
  "open-day": { label: "Open Day", icon: DoorOpen, color: "text-gold" },
  "class": { label: "Занятие", icon: Calendar, color: "text-blue-400" },
};

function RemindersTab() {
  const [items, setItems] = useState<ReminderItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminFetch("/api/admin/reminders")
      .then((r) => r.json())
      .then((data: ReminderItem[]) => setItems(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function setStatus(item: ReminderItem, status: ReminderStatus | null) {
    setItems((prev) => prev.map((i) => i.id === item.id && i.table === item.table ? { ...i, reminderStatus: status ?? undefined } : i));
    await adminFetch("/api/admin/reminders", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ table: item.table, id: item.id, status }),
    });
  }

  if (loading) return <LoadingSpinner />;

  const today = new Date().toISOString().split("T")[0];
  const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split("T")[0];

  const todayItems = items.filter((i) => i.eventDate === today);
  const tomorrowItems = items.filter((i) => i.eventDate === tomorrow);

  // Stats
  function countByStatus(list: ReminderItem[]) {
    const coming = list.filter((i) => i.reminderStatus === "coming").length;
    const cancelled = list.filter((i) => i.reminderStatus === "cancelled").length;
    const pending = list.filter((i) => i.reminderStatus === "pending").length;
    const notAsked = list.filter((i) => !i.reminderStatus).length;
    return { coming, cancelled, pending, notAsked, total: list.length };
  }

  if (items.length === 0) {
    return (
      <div className="py-12 text-center">
        <Bell size={32} className="mx-auto text-neutral-600 mb-3" />
        <p className="text-neutral-400">Нет напоминаний — все на контроле</p>
        <p className="text-xs text-neutral-600 mt-1">Здесь появятся записи на сегодня и завтра</p>
      </div>
    );
  }

  // Group items by event within each day
  function groupByEvent(dayItems: ReminderItem[]) {
    const map: Record<string, { type: ReminderItem["type"]; label: string; items: ReminderItem[] }> = {};
    for (const item of dayItems) {
      const key = `${item.type}|${item.eventLabel}`;
      if (!map[key]) map[key] = { type: item.type, label: item.eventLabel, items: [] };
      map[key].items.push(item);
    }
    return Object.values(map);
  }

  const STATUS_SECTIONS = [
    { key: "not-asked", label: "Не спрошены", color: "text-gold", bg: "bg-gold/10", match: (i: ReminderItem) => !i.reminderStatus },
    { key: "pending", label: "Нет ответа", color: "text-amber-400", bg: "bg-amber-500/10", match: (i: ReminderItem) => i.reminderStatus === "pending" },
    { key: "coming", label: "Придёт", color: "text-emerald-400", bg: "bg-emerald-500/10", match: (i: ReminderItem) => i.reminderStatus === "coming" },
    { key: "cancelled", label: "Не придёт", color: "text-red-400", bg: "bg-red-500/10", match: (i: ReminderItem) => i.reminderStatus === "cancelled" },
  ];

  function renderPerson(item: ReminderItem) {
    const currentStatus = item.reminderStatus as ReminderStatus | undefined;
    return (
      <div
        key={`${item.table}-${item.id}`}
        className={`rounded-lg border p-3 transition-colors ${
          !currentStatus ? "border-gold/20 bg-gold/[0.03]"
            : currentStatus === "coming" ? "border-emerald-500/15 bg-emerald-500/[0.02]"
            : currentStatus === "cancelled" ? "border-red-500/15 bg-red-500/[0.02] opacity-50"
            : currentStatus === "pending" ? "border-amber-500/15 bg-amber-500/[0.02]"
            : "border-white/5 bg-neutral-800/30"
        }`}
      >
        <div className="flex items-center gap-2 flex-wrap text-sm">
          <span className="font-medium text-white">{item.name}</span>
          {item.phone && (
            <a href={`tel:${item.phone}`} className="inline-flex items-center gap-1 text-emerald-400 hover:text-emerald-300 text-xs">
              <Phone size={10} />{item.phone}
            </a>
          )}
          {item.instagram && (
            <a href={`https://ig.me/m/${item.instagram.replace(/^@/, "")}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-pink-400 hover:text-pink-300 text-xs">
              <Instagram size={10} />{item.instagram}
            </a>
          )}
          {item.telegram && (
            <a href={`https://t.me/${item.telegram.replace(/^@/, "")}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-blue-400 hover:text-blue-300 text-xs">
              <Send size={10} />{item.telegram}
            </a>
          )}
          <div className="flex gap-1 ml-auto">
            {(["coming", "pending", "cancelled"] as ReminderStatus[]).map((st) => {
              const conf = STATUS_CONFIG[st];
              const Icon = conf.icon;
              const active = currentStatus === st;
              return (
                <button
                  key={st}
                  onClick={() => setStatus(item, active ? null : st)}
                  className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium transition-all ${
                    active
                      ? `${conf.bg} ${conf.color} border ${conf.border}`
                      : "bg-neutral-800/50 text-neutral-500 border border-transparent hover:border-white/10 hover:text-neutral-300"
                  }`}
                >
                  <Icon size={10} />
                  {conf.label}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {[
        { label: "Сегодня", date: today, items: todayItems },
        { label: "Завтра", date: tomorrow, items: tomorrowItems },
      ]
        .filter((g) => g.items.length > 0)
        .map((group) => {
          const eventGroups = groupByEvent(group.items);
          return (
            <div key={group.date}>
              <div className="flex items-center gap-3 mb-3">
                <h3 className="text-sm font-bold text-white">{group.label}</h3>
                <span className="text-[10px] text-neutral-500">
                  {new Date(group.date + "T12:00").toLocaleDateString("ru-RU", { weekday: "long", day: "numeric", month: "long" })}
                </span>
              </div>

              <div className="space-y-3">
                {eventGroups.map((eg) => {
                  const typeConf = TYPE_CONFIG[eg.type];
                  const TypeIcon = typeConf.icon;
                  const egStats = countByStatus(eg.items);
                  return (
                    <div key={eg.label} className="rounded-xl border border-white/10 overflow-hidden">
                      <div className="flex items-center gap-2 px-4 py-2.5 bg-neutral-900">
                        <TypeIcon size={13} className={typeConf.color} />
                        <span className="text-sm font-medium text-white">{eg.label}</span>
                        <span className="text-[10px] text-neutral-500 bg-neutral-800 rounded-full px-2 py-0.5">{eg.items.length} чел.</span>
                        <div className="flex gap-2 ml-auto text-[10px]">
                          {egStats.coming > 0 && <span className="text-emerald-400">{egStats.coming} придёт</span>}
                          {egStats.cancelled > 0 && <span className="text-red-400">{egStats.cancelled} не придёт</span>}
                          {egStats.pending > 0 && <span className="text-amber-400">{egStats.pending} нет ответа</span>}
                          {egStats.notAsked > 0 && <span className="text-gold">{egStats.notAsked} не спрошены</span>}
                        </div>
                      </div>
                      <div className="px-4 pb-3 pt-1">
                        {STATUS_SECTIONS
                          .map((sec) => ({ ...sec, items: eg.items.filter(sec.match) }))
                          .filter((sec) => sec.items.length > 0)
                          .map((sec) => (
                            <div key={sec.key} className="mt-2 first:mt-0">
                              <span className={`text-[10px] font-medium ${sec.color} ${sec.bg} rounded-full px-2 py-0.5`}>
                                {sec.label} · {sec.items.length}
                              </span>
                              <div className="mt-1.5 space-y-1.5">
                                {sec.items.map(renderPerson)}
                              </div>
                            </div>
                          ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
    </div>
  );
}

// --- Shared helpers ---

function LoadingSpinner() {
  return (
    <div className="flex items-center gap-2 py-8 text-neutral-500 justify-center">
      <Loader2 size={16} className="animate-spin" />
      Загрузка...
    </div>
  );
}

function EmptyState({ total }: { total: number }) {
  return (
    <p className="text-sm text-neutral-500 py-8 text-center">
      {total === 0 ? "Пока нет записей" : "Нет записей по фильтру"}
    </p>
  );
}

function DeleteBtn({ onClick }: { onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="rounded p-1 text-neutral-500 hover:text-red-400 transition-colors"
      title="Удалить"
    >
      <Trash2 size={14} />
    </button>
  );
}

function fmtDate(iso: string): string {
  return new Date(iso).toLocaleDateString("ru-RU");
}

// --- Main Page ---

const TABS: { key: Tab; label: string }[] = [
  { key: "reminders", label: "Напоминания" },
  { key: "classes", label: "Занятия" },
  { key: "master-classes", label: "Мастер-классы" },
  { key: "open-day", label: "День открытых дверей" },
];

export default function BookingsPage() {
  const [tab, setTab] = useState<Tab>("reminders");

  return (
    <div>
      <h1 className="text-2xl font-bold">Записи</h1>
      <p className="mt-1 text-neutral-400 text-sm">
        Все заявки и записи в одном месте
      </p>

      {/* Tabs */}
      <div className="mt-5 flex border-b border-white/10">
        {TABS.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={`px-4 py-2.5 text-sm font-medium transition-colors relative ${
              tab === t.key
                ? "text-gold"
                : "text-neutral-400 hover:text-white"
            }`}
          >
            {t.label}
            {tab === t.key && (
              <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-gold rounded-full" />
            )}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="mt-4">
        {tab === "reminders" && <RemindersTab />}
        {tab === "classes" && <GroupBookingsTab />}
        {tab === "master-classes" && <McRegistrationsTab />}
        {tab === "open-day" && <OpenDayBookingsTab />}
      </div>
    </div>
  );
}
