"use client";

import { useMemo, useState, useTransition } from "react";
import { Plus, Pencil, Trash2, Loader2, FileText, Images, Inbox } from "lucide-react";
import {
  saveVisaTypeAction,
  deleteVisaTypeAction,
  saveVisaSlideAction,
  deleteVisaSlideAction,
  updateVisaEnquiryStatusAction,
  deleteVisaEnquiryAction,
} from "./actions";

type VisaTypeRow = {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  iconKey: string | null;
  badge: string | null;
  colorClass: string | null;
  sortOrder: number;
  isActive: boolean;
};

type VisaSlideRow = {
  id: string;
  imageUrl: string;
  badge: string | null;
  badgeIcon: string | null;
  title: string | null;
  highlight: string | null;
  description: string | null;
  subtitle: string | null;
  ctaText: string | null;
  ctaLink: string | null;
  ctaSecondaryText: string | null;
  ctaSecondaryLink: string | null;
  stat1Label: string | null;
  stat1Value: string | null;
  stat2Label: string | null;
  stat2Value: string | null;
  stat3Label: string | null;
  stat3Value: string | null;
  sortOrder: number;
  isActive: boolean;
};

type VisaEnquiryRow = {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  visaType: string | null;
  destination: string | null;
  message: string | null;
  status: "new" | "in_progress" | "resolved";
  createdAt: string;
  visaTypeId: string | null;
  visaTypeRef: { id: string; name: string; slug: string } | null;
  user: { id: string; name: string; email: string } | null;
};

type Props = {
  types: VisaTypeRow[];
  slides: VisaSlideRow[];
  enquiries: VisaEnquiryRow[];
};

const emptyTypeForm = {
  id: "",
  name: "",
  slug: "",
  description: "",
  iconKey: "globe",
  badge: "",
  colorClass: "bg-neutral-50 text-neutral-600 border-neutral-200",
  sortOrder: "0",
  isActive: true,
};

const emptySlideForm = {
  id: "",
  imageUrl: "",
  badge: "",
  badgeIcon: "globe",
  title: "",
  highlight: "",
  description: "",
  subtitle: "",
  ctaText: "",
  ctaLink: "",
  ctaSecondaryText: "",
  ctaSecondaryLink: "",
  stat1Label: "",
  stat1Value: "",
  stat2Label: "",
  stat2Value: "",
  stat3Label: "",
  stat3Value: "",
  sortOrder: "0",
  isActive: true,
};

export default function AdminVisaClient({ types, slides, enquiries }: Props) {
  const [tab, setTab] = useState<"types" | "slider" | "crm">("types");
  const [pending, startTransition] = useTransition();
  const [typeForm, setTypeForm] = useState(emptyTypeForm);
  const [slideForm, setSlideForm] = useState(emptySlideForm);

  const sortedEnquiries = useMemo(
    () => [...enquiries].sort((a, b) => +new Date(b.createdAt) - +new Date(a.createdAt)),
    [enquiries]
  );

  function onSaveType(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData();
    Object.entries(typeForm).forEach(([k, v]) => fd.set(k, String(v)));

    startTransition(async () => {
      const res = await saveVisaTypeAction(fd);
      if (res.ok) {
        setTypeForm(emptyTypeForm);
      } else {
        alert(res.error || "Failed to save visa type");
      }
    });
  }

  function onSaveSlide(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    const fd = new FormData(form);
    fd.set("id", slideForm.id);
    fd.set("isActive", String(slideForm.isActive));

    startTransition(async () => {
      const res = await saveVisaSlideAction(fd);
      if (res.ok) {
        setSlideForm(emptySlideForm);
        form.reset();
      } else {
        alert(res.error || "Failed to save slide");
      }
    });
  }

  return (
    <div className="p-8 space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-neutral-900">Visa CMS & CRM</h1>
        <p className="text-sm text-neutral-500 mt-1">Manage visa types, hero slider, and customer enquiries.</p>
      </div>

      <div className="flex flex-wrap gap-2">
        {[
          { key: "types", label: "Visa Types", icon: FileText },
          { key: "slider", label: "Hero Slider", icon: Images },
          { key: "crm", label: "Enquiry CRM", icon: Inbox },
        ].map(({ key, label, icon: Icon }) => (
          <button
            key={key}
            onClick={() => setTab(key as "types" | "slider" | "crm")}
            className={`inline-flex items-center gap-2 px-4 py-2 rounded-xl text-sm border transition-colors ${
              tab === key ? "bg-navy-700 text-white border-navy-700" : "bg-white text-neutral-700 border-neutral-200 hover:border-navy-300"
            }`}
          >
            <Icon size={15} /> {label}
          </button>
        ))}
      </div>

      {tab === "types" && (
        <div className="grid lg:grid-cols-5 gap-6">
          <form onSubmit={onSaveType} className="lg:col-span-2 bg-white border border-neutral-200 rounded-2xl p-5 space-y-3">
            <h2 className="font-semibold text-neutral-900">{typeForm.id ? "Edit Visa Type" : "Add Visa Type"}</h2>
            <input value={typeForm.id} readOnly hidden name="id" />

            <input
              value={typeForm.name}
              onChange={(e) => setTypeForm((s) => ({ ...s, name: e.target.value }))}
              placeholder="Name"
              className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              required
            />
            <input
              value={typeForm.slug}
              onChange={(e) => setTypeForm((s) => ({ ...s, slug: e.target.value }))}
              placeholder="Slug (optional)"
              className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
            />
            <textarea
              value={typeForm.description}
              onChange={(e) => setTypeForm((s) => ({ ...s, description: e.target.value }))}
              placeholder="Description"
              rows={3}
              className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
            />
            <div className="grid grid-cols-2 gap-2">
              <input
                value={typeForm.iconKey}
                onChange={(e) => setTypeForm((s) => ({ ...s, iconKey: e.target.value }))}
                placeholder="Icon key"
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              />
              <input
                value={typeForm.badge}
                onChange={(e) => setTypeForm((s) => ({ ...s, badge: e.target.value }))}
                placeholder="Badge text"
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              />
            </div>
            <input
              value={typeForm.colorClass}
              onChange={(e) => setTypeForm((s) => ({ ...s, colorClass: e.target.value }))}
              placeholder="Tailwind color classes"
              className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
            />
            <div className="grid grid-cols-2 gap-2">
              <input
                type="number"
                value={typeForm.sortOrder}
                onChange={(e) => setTypeForm((s) => ({ ...s, sortOrder: e.target.value }))}
                placeholder="Sort order"
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              />
              <select
                value={String(typeForm.isActive)}
                onChange={(e) => setTypeForm((s) => ({ ...s, isActive: e.target.value === "true" }))}
                className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm"
              >
                <option value="true">Active</option>
                <option value="false">Inactive</option>
              </select>
            </div>

            <div className="flex gap-2">
              <button type="submit" disabled={pending} className="inline-flex items-center gap-2 px-4 py-2 bg-navy-700 text-white rounded-lg text-sm font-medium">
                {pending ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />} Save Type
              </button>
              <button type="button" onClick={() => setTypeForm(emptyTypeForm)} className="px-4 py-2 border border-neutral-300 rounded-lg text-sm">
                Reset
              </button>
            </div>
          </form>

          <div className="lg:col-span-3 bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-neutral-50 text-xs uppercase text-neutral-500">
                <tr>
                  <th className="text-left px-4 py-3">Name</th>
                  <th className="text-left px-4 py-3">Slug</th>
                  <th className="text-left px-4 py-3">Status</th>
                  <th className="text-left px-4 py-3">Actions</th>
                </tr>
              </thead>
              <tbody>
                {types.map((row) => (
                  <tr key={row.id} className="border-t border-neutral-100">
                    <td className="px-4 py-3 font-medium text-neutral-900">{row.name}</td>
                    <td className="px-4 py-3 text-neutral-500">{row.slug}</td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs ${row.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-200 text-neutral-600"}`}>
                        {row.isActive ? "Active" : "Inactive"}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-2">
                        <button
                          onClick={() =>
                            setTypeForm({
                              id: row.id,
                              name: row.name,
                              slug: row.slug,
                              description: row.description || "",
                              iconKey: row.iconKey || "globe",
                              badge: row.badge || "",
                              colorClass: row.colorClass || "",
                              sortOrder: String(row.sortOrder),
                              isActive: row.isActive,
                            })
                          }
                          className="p-2 rounded-lg border border-neutral-300 hover:bg-neutral-50"
                          title="Edit"
                        >
                          <Pencil size={14} />
                        </button>
                        <button
                          onClick={() =>
                            startTransition(async () => {
                              const ok = confirm(`Delete ${row.name}?`);
                              if (!ok) return;
                              const res = await deleteVisaTypeAction(row.id);
                              if (!res.ok) alert(res.error || "Failed to delete");
                            })
                          }
                          className="p-2 rounded-lg border border-red-200 text-red-600 hover:bg-red-50"
                          title="Delete"
                        >
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "slider" && (
        <div className="grid lg:grid-cols-5 gap-6">
          <form onSubmit={onSaveSlide} className="lg:col-span-2 bg-white border border-neutral-200 rounded-2xl p-5 space-y-3">
            <h2 className="font-semibold text-neutral-900">{slideForm.id ? "Edit Slider Item" : "Add Slider Item"}</h2>
            <input value={slideForm.id} readOnly hidden name="id" />
            <input name="imageUrl" value={slideForm.imageUrl} onChange={(e) => setSlideForm((s) => ({ ...s, imageUrl: e.target.value }))} placeholder="Image URL" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            <input name="imageFile" type="file" accept="image/*" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            <div className="grid grid-cols-2 gap-2">
              <input name="badge" value={slideForm.badge} onChange={(e) => setSlideForm((s) => ({ ...s, badge: e.target.value }))} placeholder="Badge" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="badgeIcon" value={slideForm.badgeIcon} onChange={(e) => setSlideForm((s) => ({ ...s, badgeIcon: e.target.value }))} placeholder="Badge icon key" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            </div>
            <input name="title" value={slideForm.title} onChange={(e) => setSlideForm((s) => ({ ...s, title: e.target.value }))} placeholder="Title" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            <input name="highlight" value={slideForm.highlight} onChange={(e) => setSlideForm((s) => ({ ...s, highlight: e.target.value }))} placeholder="Highlight" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            <textarea name="description" value={slideForm.description} onChange={(e) => setSlideForm((s) => ({ ...s, description: e.target.value }))} placeholder="Description" rows={3} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            <div className="grid grid-cols-2 gap-2">
              <input name="ctaText" value={slideForm.ctaText} onChange={(e) => setSlideForm((s) => ({ ...s, ctaText: e.target.value }))} placeholder="Primary CTA text" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="ctaLink" value={slideForm.ctaLink} onChange={(e) => setSlideForm((s) => ({ ...s, ctaLink: e.target.value }))} placeholder="Primary CTA link" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            </div>
            <div className="grid grid-cols-2 gap-2">
              <input name="ctaSecondaryText" value={slideForm.ctaSecondaryText} onChange={(e) => setSlideForm((s) => ({ ...s, ctaSecondaryText: e.target.value }))} placeholder="Secondary CTA text" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="ctaSecondaryLink" value={slideForm.ctaSecondaryLink} onChange={(e) => setSlideForm((s) => ({ ...s, ctaSecondaryLink: e.target.value }))} placeholder="Secondary CTA link" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            </div>
            <div className="grid grid-cols-2 gap-2">
              <input name="stat1Value" value={slideForm.stat1Value} onChange={(e) => setSlideForm((s) => ({ ...s, stat1Value: e.target.value }))} placeholder="Stat 1 value" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="stat1Label" value={slideForm.stat1Label} onChange={(e) => setSlideForm((s) => ({ ...s, stat1Label: e.target.value }))} placeholder="Stat 1 label" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="stat2Value" value={slideForm.stat2Value} onChange={(e) => setSlideForm((s) => ({ ...s, stat2Value: e.target.value }))} placeholder="Stat 2 value" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="stat2Label" value={slideForm.stat2Label} onChange={(e) => setSlideForm((s) => ({ ...s, stat2Label: e.target.value }))} placeholder="Stat 2 label" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="stat3Value" value={slideForm.stat3Value} onChange={(e) => setSlideForm((s) => ({ ...s, stat3Value: e.target.value }))} placeholder="Stat 3 value" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <input name="stat3Label" value={slideForm.stat3Label} onChange={(e) => setSlideForm((s) => ({ ...s, stat3Label: e.target.value }))} placeholder="Stat 3 label" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
            </div>
            <div className="grid grid-cols-2 gap-2">
              <input name="sortOrder" type="number" value={slideForm.sortOrder} onChange={(e) => setSlideForm((s) => ({ ...s, sortOrder: e.target.value }))} placeholder="Sort order" className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm" />
              <select value={String(slideForm.isActive)} onChange={(e) => setSlideForm((s) => ({ ...s, isActive: e.target.value === "true" }))} className="w-full border border-neutral-300 rounded-lg px-3 py-2 text-sm">
                <option value="true">Active</option>
                <option value="false">Inactive</option>
              </select>
            </div>

            <div className="flex gap-2">
              <button type="submit" disabled={pending} className="inline-flex items-center gap-2 px-4 py-2 bg-navy-700 text-white rounded-lg text-sm font-medium">
                {pending ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />} Save Slide
              </button>
              <button type="button" onClick={() => setSlideForm(emptySlideForm)} className="px-4 py-2 border border-neutral-300 rounded-lg text-sm">
                Reset
              </button>
            </div>
          </form>

          <div className="lg:col-span-3 bg-white border border-neutral-200 rounded-2xl overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-neutral-50 text-xs uppercase text-neutral-500">
                <tr>
                  <th className="text-left px-4 py-3">Slide</th>
                  <th className="text-left px-4 py-3">Order</th>
                  <th className="text-left px-4 py-3">Status</th>
                  <th className="text-left px-4 py-3">Actions</th>
                </tr>
              </thead>
              <tbody>
                {slides.map((row) => (
                  <tr key={row.id} className="border-t border-neutral-100">
                    <td className="px-4 py-3">
                      <div className="font-medium text-neutral-900">{row.title || "Untitled"}</div>
                      <div className="text-xs text-neutral-500">{row.badge || row.imageUrl}</div>
                    </td>
                    <td className="px-4 py-3 text-neutral-600">{row.sortOrder}</td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs ${row.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-200 text-neutral-600"}`}>
                        {row.isActive ? "Active" : "Inactive"}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-2">
                        <button
                          onClick={() =>
                            setSlideForm({
                              id: row.id,
                              imageUrl: row.imageUrl,
                              badge: row.badge || "",
                              badgeIcon: row.badgeIcon || "globe",
                              title: row.title || "",
                              highlight: row.highlight || "",
                              description: row.description || "",
                              subtitle: row.subtitle || "",
                              ctaText: row.ctaText || "",
                              ctaLink: row.ctaLink || "",
                              ctaSecondaryText: row.ctaSecondaryText || "",
                              ctaSecondaryLink: row.ctaSecondaryLink || "",
                              stat1Label: row.stat1Label || "",
                              stat1Value: row.stat1Value || "",
                              stat2Label: row.stat2Label || "",
                              stat2Value: row.stat2Value || "",
                              stat3Label: row.stat3Label || "",
                              stat3Value: row.stat3Value || "",
                              sortOrder: String(row.sortOrder),
                              isActive: row.isActive,
                            })
                          }
                          className="p-2 rounded-lg border border-neutral-300 hover:bg-neutral-50"
                          title="Edit"
                        >
                          <Pencil size={14} />
                        </button>
                        <button
                          onClick={() =>
                            startTransition(async () => {
                              const ok = confirm("Delete this slide?");
                              if (!ok) return;
                              await deleteVisaSlideAction(row.id);
                            })
                          }
                          className="p-2 rounded-lg border border-red-200 text-red-600 hover:bg-red-50"
                          title="Delete"
                        >
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "crm" && (
        <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-neutral-50 text-xs uppercase text-neutral-500">
              <tr>
                <th className="text-left px-4 py-3">Lead</th>
                <th className="text-left px-4 py-3">Visa</th>
                <th className="text-left px-4 py-3">Destination</th>
                <th className="text-left px-4 py-3">Status</th>
                <th className="text-left px-4 py-3">Date</th>
                <th className="text-left px-4 py-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {sortedEnquiries.map((row) => (
                <tr key={row.id} className="border-t border-neutral-100 align-top">
                  <td className="px-4 py-3">
                    <div className="font-medium text-neutral-900">{row.name}</div>
                    <div className="text-xs text-neutral-500">{row.email}{row.phone ? ` · ${row.phone}` : ""}</div>
                    {row.message ? <div className="text-xs text-neutral-600 mt-1 line-clamp-2">{row.message}</div> : null}
                  </td>
                  <td className="px-4 py-3 text-neutral-700">{row.visaTypeRef?.name || row.visaType || "-"}</td>
                  <td className="px-4 py-3 text-neutral-700">{row.destination || "-"}</td>
                  <td className="px-4 py-3">
                    <select
                      value={row.status}
                      onChange={(e) =>
                        startTransition(async () => {
                          await updateVisaEnquiryStatusAction(row.id, e.target.value as "new" | "in_progress" | "resolved");
                        })
                      }
                      className="border border-neutral-300 rounded-lg px-2 py-1.5 text-xs"
                    >
                      <option value="new">New</option>
                      <option value="in_progress">In Progress</option>
                      <option value="resolved">Resolved</option>
                    </select>
                  </td>
                  <td className="px-4 py-3 text-neutral-500">{new Date(row.createdAt).toLocaleString()}</td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() =>
                        startTransition(async () => {
                          const ok = confirm("Delete this enquiry?");
                          if (!ok) return;
                          await deleteVisaEnquiryAction(row.id);
                        })
                      }
                      className="p-2 rounded-lg border border-red-200 text-red-600 hover:bg-red-50"
                      title="Delete"
                    >
                      <Trash2 size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
