"use client";

import { useState, useTransition } from "react";
import {
  GraduationCap, Plus, Edit2, Trash2, X, CheckCircle, XCircle,
  Loader2, Eye, EyeOff, Search, ExternalLink, Calendar,
} from "lucide-react";
import {
  saveScholarshipAction,
  deleteScholarshipAction,
  toggleScholarshipActiveAction,
} from "./actions";

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

type Scholarship = {
  id: string;
  title: string;
  provider: string | null;
  country: string | null;
  amount: string | null;
  deadline: string | null;
  description: string | null;
  applyLink: string | null;
  isActive: boolean;
  createdAt: string;
};

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

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>
  );
}

// ─── Form ─────────────────────────────────────────────────────────────────────

function ScholarshipForm({ scholarship, onClose, onDone }: {
  scholarship?: Scholarship;
  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 saveScholarshipAction(fd);
      if (res?.error) { onDone("err:" + res.error); }
      else { onDone("Scholarship saved."); onClose(); }
    });
  }

  const deadlineVal = scholarship?.deadline
    ? new Date(scholarship.deadline).toISOString().split("T")[0]
    : "";

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {scholarship && <input type="hidden" name="id" value={scholarship.id} />}
      <Field label="Title *">
        <input name="title" defaultValue={scholarship?.title ?? ""} required className={inp} placeholder="Chevening Scholarships 2026/27" />
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Provider / Organization">
          <input name="provider" defaultValue={scholarship?.provider ?? ""} className={inp} placeholder="UK Government" />
        </Field>
        <Field label="Country">
          <input name="country" defaultValue={scholarship?.country ?? ""} className={inp} placeholder="United Kingdom" />
        </Field>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Amount / Funding">
          <input name="amount" defaultValue={scholarship?.amount ?? ""} className={inp} placeholder="Full Funding" />
        </Field>
        <Field label="Application Deadline">
          <input name="deadline" type="date" defaultValue={deadlineVal} className={inp} />
        </Field>
      </div>
      <Field label="Description">
        <textarea name="description" defaultValue={scholarship?.description ?? ""} rows={4} className={inp} placeholder="Describe the scholarship, eligibility, requirements..." />
      </Field>
      <div className="grid grid-cols-2 gap-4">
        <Field label="Apply Link">
          <input name="applyLink" defaultValue={scholarship?.applyLink ?? ""} className={inp} placeholder="https://..." />
        </Field>
        <Field label="Status">
          <select name="isActive" defaultValue={scholarship?.isActive !== false ? "true" : "false"} className={sel}>
            <option value="true">Active — show on site</option>
            <option value="false">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" />}
          {scholarship ? "Save Changes" : "Add Scholarship"}
        </button>
      </div>
    </form>
  );
}

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

export default function AdminScholarshipsClient({ scholarships }: { scholarships: Scholarship[] }) {
  const [search, setSearch] = useState("");
  const [editItem, setEditItem] = useState<Scholarship | null>(null);
  const [showNew, setShowNew] = useState(false);
  const [isPending, startTransition] = useTransition();
  const { show, Toast } = useToast();

  const filtered = scholarships.filter(s =>
    `${s.title} ${s.provider ?? ""} ${s.country ?? ""}`.toLowerCase().includes(search.toLowerCase())
  );

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

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

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

      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-neutral-900">Scholarships</h1>
          <p className="text-neutral-500 text-sm mt-0.5">Manage all scholarship listings shown on the site.</p>
        </div>
        <button
          onClick={() => { setShowNew(true); setEditItem(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={16} /> Add Scholarship
        </button>
      </div>

      {/* Search */}
      <div className="bg-white rounded-2xl border border-neutral-200 overflow-hidden mb-4">
        <div className="p-4 border-b border-neutral-100 flex items-center justify-between">
          <div className="relative max-w-sm w-full">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400" />
            <input
              type="search"
              placeholder="Search scholarships..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              className="w-full pl-9 pr-4 py-2 border border-neutral-200 rounded-lg text-sm focus:outline-none focus:border-navy-400"
            />
          </div>
          <span className="text-sm text-neutral-400">{filtered.length} result{filtered.length !== 1 ? "s" : ""}</span>
        </div>

        {filtered.length === 0 ? (
          <div className="p-12 text-center">
            <GraduationCap size={36} className="text-neutral-300 mx-auto mb-3" />
            <p className="text-neutral-500 text-sm">
              {search ? "No scholarships match your search." : "No scholarships yet. Add your first one!"}
            </p>
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-neutral-50 text-xs font-semibold text-neutral-500 uppercase tracking-wide">
              <tr>
                <th className="px-4 py-3 text-left">Title</th>
                <th className="px-4 py-3 text-left hidden md:table-cell">Provider</th>
                <th className="px-4 py-3 text-left hidden lg:table-cell">Country</th>
                <th className="px-4 py-3 text-left hidden md:table-cell">Amount</th>
                <th className="px-4 py-3 text-left hidden lg:table-cell">Deadline</th>
                <th className="px-4 py-3 text-center">Status</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100">
              {filtered.map((s) => (
                <tr key={s.id} className="hover:bg-neutral-50 transition-colors">
                  <td className="px-4 py-3">
                    <p className="font-medium text-neutral-800 line-clamp-1">{s.title}</p>
                    {s.applyLink && (
                      <a href={s.applyLink} target="_blank" rel="noopener noreferrer" className="text-[11px] text-navy-500 hover:underline flex items-center gap-0.5 mt-0.5">
                        <ExternalLink size={10} /> Apply Link
                      </a>
                    )}
                  </td>
                  <td className="px-4 py-3 text-neutral-500 hidden md:table-cell">{s.provider ?? "—"}</td>
                  <td className="px-4 py-3 text-neutral-500 hidden lg:table-cell">{s.country ?? "—"}</td>
                  <td className="px-4 py-3 text-emerald-600 font-medium hidden md:table-cell">{s.amount ?? "—"}</td>
                  <td className="px-4 py-3 text-neutral-500 hidden lg:table-cell">
                    {s.deadline ? (
                      <span className="flex items-center gap-1"><Calendar size={12} /> {new Date(s.deadline).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</span>
                    ) : "—"}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span className={`inline-block text-[11px] font-semibold px-2.5 py-0.5 rounded-full ${s.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-100 text-neutral-500"}`}>
                      {s.isActive ? "Active" : "Hidden"}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-1">
                      <button onClick={() => handleToggle(s.id, s.isActive)} disabled={isPending} className="p-1.5 text-neutral-400 hover:text-navy-700 rounded hover:bg-neutral-100" title={s.isActive ? "Disable" : "Enable"}>
                        {s.isActive ? <EyeOff size={14} /> : <Eye size={14} />}
                      </button>
                      <button onClick={() => { setEditItem(s); setShowNew(false); }} className="p-1.5 text-neutral-400 hover:text-navy-700 rounded hover:bg-neutral-100">
                        <Edit2 size={14} />
                      </button>
                      <button onClick={() => handleDelete(s.id)} className="p-1.5 text-neutral-400 hover:text-red-600 rounded hover:bg-red-50">
                        <Trash2 size={14} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Modals */}
      {showNew && (
        <Modal title="Add Scholarship" onClose={() => setShowNew(false)}>
          <ScholarshipForm onClose={() => setShowNew(false)} onDone={(msg) => { if (msg.startsWith("err:")) show("err", msg.slice(4)); else show("ok", msg); }} />
        </Modal>
      )}
      {editItem && (
        <Modal title="Edit Scholarship" onClose={() => setEditItem(null)}>
          <ScholarshipForm scholarship={editItem} onClose={() => setEditItem(null)} onDone={(msg) => { if (msg.startsWith("err:")) show("err", msg.slice(4)); else show("ok", msg); }} />
        </Modal>
      )}
    </div>
  );
}
