"use client";

import { useState, useTransition } from "react";
import {
  Images, Plus, Edit2, Trash2, X, CheckCircle, XCircle, Loader2,
  Eye, EyeOff, BarChart3, Users, Briefcase, GraduationCap, Package, Plane,
  GripVertical, Globe,
} from "lucide-react";
import {
  saveHeroSlideAction,
  deleteHeroSlideAction,
  toggleHeroSlideActiveAction,
} from "./actions";

// ─── Types ────────────────────────────────────────────────────────────────────

type HeroSlide = {
  id: string;
  imageUrl: string;
  badge: string | null;
  badgeIcon: string | null;
  title: string | null;
  highlight: string | null;
  description: string | null;
  ctaLabel: string | null;
  ctaHref: string | null;
  ctaSecondLabel: string | null;
  ctaSecondHref: string | null;
  sortOrder: number;
  isActive: boolean;
};

type Stats = {
  users: number;
  jobs: number;
  scholarships: number;
  products: number;
  journals: number;
  tours: number;
  orders: number;
  subscribers: number;
};

type Props = {
  heroSlides: HeroSlide[];
  stats: Stats;
};

// ─── Helpers ──────────────────────────────────────────────────────────────────

const BADGE_ICONS = ["jobs", "scholarships", "shop", "journal", "tours", "visa"];

function useToast() {
  const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
  function show(type: "ok" | "err", text: string) {
    setMsg({ type, text });
    setTimeout(() => setMsg(null), 4000);
  }
  const Toast = msg ? (
    <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-2.5 px-4 py-3 rounded-xl shadow-lg text-sm font-medium border ${msg.type === "ok" ? "bg-emerald-50 text-emerald-800 border-emerald-200" : "bg-red-50 text-red-700 border-red-200"}`}>
      {msg.type === "ok" ? <CheckCircle size={16} /> : <XCircle size={16} />}
      {msg.text}
    </div>
  ) : null;
  return { show, Toast };
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-neutral-100">
          <h3 className="font-bold text-neutral-800">{title}</h3>
          <button onClick={onClose} className="text-neutral-400 hover:text-neutral-600"><X size={18} /></button>
        </div>
        <div className="p-6">{children}</div>
      </div>
    </div>
  );
}

const inp = "w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-navy-500";
const sel = "w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-navy-500 bg-white";

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-1">{label}</label>
      {children}
    </div>
  );
}

// ─── Hero Slide Form ──────────────────────────────────────────────────────────

function SlideForm({ slide, onClose, onDone }: { slide?: HeroSlide; onClose: () => void; onDone: (msg: string) => void }) {
  const [isPending, startTransition] = useTransition();

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    startTransition(async () => {
      const res = await saveHeroSlideAction(fd);
      if (res?.error) { onDone("err:" + res.error); }
      else { onDone("Hero slide saved."); onClose(); }
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {slide && <input type="hidden" name="id" value={slide.id} />}
      <Field label="Image URL *">
        <input name="imageUrl" defaultValue={slide?.imageUrl ?? ""} required className={inp} placeholder="https://..." />
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Badge Text">
          <input name="badge" defaultValue={slide?.badge ?? ""} className={inp} placeholder="Jobs Portal" />
        </Field>
        <Field label="Badge Icon">
          <select name="badgeIcon" defaultValue={slide?.badgeIcon ?? "jobs"} className={sel}>
            {BADGE_ICONS.map(icon => <option key={icon} value={icon}>{icon}</option>)}
          </select>
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Title (line 1)">
          <input name="title" defaultValue={slide?.title ?? ""} className={inp} placeholder="Find Your" />
        </Field>
        <Field label="Highlight (line 2, gold)">
          <input name="highlight" defaultValue={slide?.highlight ?? ""} className={inp} placeholder="Dream Career" />
        </Field>
      </div>
      <Field label="Description">
        <textarea name="description" defaultValue={slide?.description ?? ""} rows={3} className={inp} placeholder="Short description shown below the title..." />
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Primary CTA Label">
          <input name="ctaLabel" defaultValue={slide?.ctaLabel ?? ""} className={inp} placeholder="Browse Jobs" />
        </Field>
        <Field label="Primary CTA Link">
          <input name="ctaHref" defaultValue={slide?.ctaHref ?? ""} className={inp} placeholder="/jobs" />
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Secondary CTA Label">
          <input name="ctaSecondLabel" defaultValue={slide?.ctaSecondLabel ?? ""} className={inp} placeholder="Learn More" />
        </Field>
        <Field label="Secondary CTA Link">
          <input name="ctaSecondHref" defaultValue={slide?.ctaSecondHref ?? ""} className={inp} placeholder="/about" />
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Sort Order">
          <input name="sortOrder" type="number" defaultValue={slide?.sortOrder ?? 0} className={inp} />
        </Field>
        <Field label="Active">
          <select name="isActive" defaultValue={slide?.isActive !== false ? "true" : "false"} className={sel}>
            <option value="true">Yes — visible on homepage</option>
            <option value="false">No — hidden</option>
          </select>
        </Field>
      </div>
      <div className="flex justify-end gap-3 pt-2">
        <button type="button" onClick={onClose} className="px-4 py-2 text-sm font-medium text-neutral-600 hover:text-neutral-800">Cancel</button>
        <button type="submit" disabled={isPending} className="flex items-center gap-2 px-5 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-60">
          {isPending && <Loader2 size={14} className="animate-spin" />}
          {slide ? "Save Changes" : "Add Slide"}
        </button>
      </div>
    </form>
  );
}

// ─── Main Client ──────────────────────────────────────────────────────────────

const TABS = [
  { id: "slides", label: "Hero Slides", icon: Images },
  { id: "stats", label: "Live Stats", icon: BarChart3 },
] as const;
type TabId = (typeof TABS)[number]["id"];

export default function AdminHomeClient({ heroSlides, stats }: Props) {
  const [tab, setTab] = useState<TabId>("slides");
  const [editSlide, setEditSlide] = useState<HeroSlide | null>(null);
  const [showNew, setShowNew] = useState(false);
  const [isPending, startTransition] = useTransition();
  const { show, Toast } = useToast();

  function handleDelete(id: string) {
    if (!confirm("Delete this slide? This cannot be undone.")) return;
    startTransition(async () => {
      await deleteHeroSlideAction(id);
      show("ok", "Slide deleted.");
    });
  }

  function handleToggle(id: string, current: boolean) {
    startTransition(async () => {
      await toggleHeroSlideActiveAction(id, !current);
      show("ok", `Slide ${!current ? "enabled" : "disabled"}.`);
    });
  }

  return (
    <div className="p-8">
      {Toast}

      {/* Header */}
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-neutral-900">Home Page Management</h1>
        <p className="text-neutral-500 text-sm mt-0.5">Manage hero slides and view live site statistics.</p>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-neutral-100 rounded-xl p-1 mb-8 w-fit">
        {TABS.map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            onClick={() => setTab(id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold transition-all ${tab === id ? "bg-white text-navy-800 shadow-sm" : "text-neutral-500 hover:text-navy-700"}`}
          >
            <Icon size={15} /> {label}
          </button>
        ))}
      </div>

      {/* ── Hero Slides Tab ── */}
      {tab === "slides" && (
        <div>
          <div className="flex items-center justify-between mb-5">
            <p className="text-sm text-neutral-500">{heroSlides.length} slide{heroSlides.length !== 1 ? "s" : ""} configured</p>
            <button
              onClick={() => { setShowNew(true); setEditSlide(null); }}
              className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800"
            >
              <Plus size={15} /> Add Slide
            </button>
          </div>

          {heroSlides.length === 0 ? (
            <div className="bg-white rounded-2xl border border-neutral-200 p-16 text-center">
              <Images size={40} className="text-neutral-300 mx-auto mb-3" />
              <p className="font-semibold text-neutral-600 mb-1">No hero slides yet</p>
              <p className="text-sm text-neutral-400 mb-4">The homepage will show default fallback slides. Add slides here to override them.</p>
              <button onClick={() => setShowNew(true)} className="inline-flex items-center gap-2 px-4 py-2 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
                <Plus size={14} /> Add First Slide
              </button>
            </div>
          ) : (
            <div className="space-y-4">
              {heroSlides.map((slide) => (
                <div key={slide.id} className="bg-white rounded-2xl border border-neutral-200 flex gap-5 p-4 items-center">
                  <GripVertical size={16} className="text-neutral-300 shrink-0 cursor-grab" />
                  <div className="w-24 h-16 rounded-xl overflow-hidden shrink-0 bg-neutral-100">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={slide.imageUrl} alt={slide.title ?? ""} className="w-full h-full object-cover" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full ${slide.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-100 text-neutral-500"}`}>
                        {slide.isActive ? "Active" : "Hidden"}
                      </span>
                      <span className="text-[10px] text-neutral-400 font-mono">#{slide.sortOrder}</span>
                      {slide.badgeIcon && <span className="text-[10px] bg-navy-50 text-navy-600 px-2 py-0.5 rounded-full">{slide.badgeIcon}</span>}
                    </div>
                    <p className="font-semibold text-neutral-800 text-sm truncate">
                      {slide.title ?? "Untitled"} <span className="text-gold-500">{slide.highlight}</span>
                    </p>
                    <p className="text-xs text-neutral-400 truncate mt-0.5">{slide.badge ?? ""} · {slide.ctaLabel ?? ""} → {slide.ctaHref ?? ""}</p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <button
                      onClick={() => handleToggle(slide.id, slide.isActive)}
                      disabled={isPending}
                      className="p-2 text-neutral-400 hover:text-navy-700 rounded-lg hover:bg-neutral-100"
                      title={slide.isActive ? "Disable" : "Enable"}
                    >
                      {slide.isActive ? <EyeOff size={16} /> : <Eye size={16} />}
                    </button>
                    <button
                      onClick={() => { setEditSlide(slide); setShowNew(false); }}
                      className="p-2 text-neutral-400 hover:text-navy-700 rounded-lg hover:bg-neutral-100"
                    >
                      <Edit2 size={16} />
                    </button>
                    <button
                      onClick={() => handleDelete(slide.id)}
                      className="p-2 text-neutral-400 hover:text-red-600 rounded-lg hover:bg-red-50"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Modals */}
          {showNew && (
            <Modal title="Add Hero Slide" onClose={() => setShowNew(false)}>
              <SlideForm onClose={() => setShowNew(false)} onDone={(msg) => { if (msg.startsWith("err:")) show("err", msg.slice(4)); else show("ok", msg); }} />
            </Modal>
          )}
          {editSlide && (
            <Modal title="Edit Hero Slide" onClose={() => setEditSlide(null)}>
              <SlideForm slide={editSlide} onClose={() => setEditSlide(null)} onDone={(msg) => { if (msg.startsWith("err:")) show("err", msg.slice(4)); else show("ok", msg); }} />
            </Modal>
          )}
        </div>
      )}

      {/* ── Stats Tab ── */}
      {tab === "stats" && (
        <div>
          <p className="text-sm text-neutral-500 mb-5">Live counts pulled directly from the database.</p>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[
              { icon: Users, label: "Registered Users", value: stats.users, color: "bg-blue-50 text-blue-600" },
              { icon: Briefcase, label: "Active Jobs", value: stats.jobs, color: "bg-emerald-50 text-emerald-600" },
              { icon: GraduationCap, label: "Scholarships", value: stats.scholarships, color: "bg-purple-50 text-purple-600" },
              { icon: Package, label: "Products", value: stats.products, color: "bg-amber-50 text-amber-600" },
              { icon: Globe, label: "Journal Articles", value: stats.journals, color: "bg-sky-50 text-sky-600" },
              { icon: Plane, label: "Tour Packages", value: stats.tours, color: "bg-rose-50 text-rose-600" },
              { icon: Package, label: "Orders", value: stats.orders, color: "bg-orange-50 text-orange-600" },
              { icon: Users, label: "Subscribers", value: stats.subscribers, color: "bg-indigo-50 text-indigo-600" },
            ].map(({ icon: Icon, label, value, color }) => (
              <div key={label} className="bg-white rounded-2xl border border-neutral-200 p-5 flex items-center gap-4">
                <div className={`w-11 h-11 rounded-xl flex items-center justify-center shrink-0 ${color}`}>
                  <Icon size={20} />
                </div>
                <div>
                  <div className="text-2xl font-black text-neutral-900">{value.toLocaleString()}</div>
                  <div className="text-xs text-neutral-500">{label}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
