"use client";

import { useState, useEffect } from "react";
import { Plus, Pencil, Trash2, Loader2, Save, X } from "lucide-react";
import { formatDate } from "@/lib/types";

interface TimelineEvent {
  id: string; title: string; date: string;
  description: string; icon: string; category: string; sortOrder: number;
}

const CATEGORIES = [
  { value: "career", label: "شغلی" },
  { value: "product", label: "محصول" },
  { value: "personal", label: "شخصی" },
];

const emptyForm: Omit<TimelineEvent, "id"> = {
  title: "", date: new Date().toISOString().split("T")[0],
  description: "", icon: "🚀", category: "career", sortOrder: 0,
};

export default function AdminTimelinePage() {
  const [events, setEvents] = useState<TimelineEvent[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [showNew, setShowNew] = useState(false);
  const [form, setForm] = useState<Omit<TimelineEvent, "id">>(emptyForm);
  const [saving, setSaving] = useState(false);

  async function load() {
    const res = await fetch("/api/admin/timeline");
    setEvents(await res.json());
    setLoading(false);
  }
  useEffect(() => { load(); }, []);

  function startEdit(ev: TimelineEvent) {
    setForm({ title: ev.title, date: new Date(ev.date).toISOString().split("T")[0], description: ev.description ?? "", icon: ev.icon ?? "🚀", category: ev.category, sortOrder: ev.sortOrder });
    setEditingId(ev.id);
    setShowNew(false);
  }

  async function handleSave() {
    setSaving(true);
    const body = { ...form, date: new Date(form.date).toISOString() };
    if (editingId) {
      await fetch(`/api/admin/timeline/${editingId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
    } else {
      await fetch("/api/admin/timeline", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
    }
    setSaving(false);
    setEditingId(null);
    setShowNew(false);
    setForm(emptyForm);
    await load();
  }

  async function handleDelete(id: string) {
    if (!confirm("حذف شود؟")) return;
    await fetch(`/api/admin/timeline/${id}`, { method: "DELETE" });
    await load();
  }

  const showForm = showNew || editingId;

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-bold text-text-primary">تایم‌لاین</h1>
        <button onClick={() => { setShowNew(true); setEditingId(null); setForm(emptyForm); }} className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-background hover:bg-accent-hover transition-colors">
          <Plus size={16} /> رویداد جدید
        </button>
      </div>

      {showForm && (
        <div className="mb-6 rounded-xl border border-accent/20 bg-surface p-6 space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="font-semibold text-text-primary">{editingId ? "ویرایش رویداد" : "رویداد جدید"}</h2>
            <button onClick={() => { setShowNew(false); setEditingId(null); }} className="text-text-secondary hover:text-text-primary"><X size={16} /></button>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">عنوان</label>
              <input type="text" value={form.title} onChange={(e) => setForm((p) => ({ ...p, title: e.target.value }))} className="admin-input w-full" />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">تاریخ</label>
              <input type="date" value={form.date} onChange={(e) => setForm((p) => ({ ...p, date: e.target.value }))} dir="ltr" className="admin-input w-full" />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">آیکون (emoji)</label>
              <input type="text" value={form.icon} onChange={(e) => setForm((p) => ({ ...p, icon: e.target.value }))} className="admin-input w-full" maxLength={4} />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">دسته‌بندی</label>
              <select value={form.category} onChange={(e) => setForm((p) => ({ ...p, category: e.target.value }))} className="admin-input w-full">
                {CATEGORIES.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
              </select>
            </div>
            <div className="sm:col-span-2">
              <label className="block text-sm font-medium text-text-primary mb-1.5">توضیحات</label>
              <textarea value={form.description} onChange={(e) => setForm((p) => ({ ...p, description: e.target.value }))} rows={2} className="admin-input w-full resize-none" />
            </div>
          </div>
          <button onClick={handleSave} disabled={saving || !form.title} className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-background hover:bg-accent-hover disabled:opacity-60 transition-colors">
            {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
            ذخیره
          </button>
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-20"><Loader2 className="animate-spin text-text-secondary" /></div>
      ) : events.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-20 text-center">
          <p className="text-text-secondary">هنوز رویدادی ندارید</p>
        </div>
      ) : (
        <div className="space-y-3">
          {events.map((ev) => (
            <div key={ev.id} className="flex items-start gap-4 rounded-xl border border-border bg-surface p-4">
              <div className="flex h-10 w-10 items-center justify-center rounded-full border border-border bg-surface-hover text-lg shrink-0">{ev.icon ?? "●"}</div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="font-semibold text-text-primary">{ev.title}</span>
                  <span className={`rounded-full border px-2 py-0.5 font-mono text-xs ${ev.category === "career" ? "text-accent border-accent/30" : ev.category === "product" ? "text-blue-400 border-blue-400/30" : "text-purple-400 border-purple-400/30"}`}>
                    {formatDate(new Date(ev.date), "fa")}
                  </span>
                </div>
                {ev.description && <p className="mt-1 text-sm text-text-secondary">{ev.description}</p>}
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <button onClick={() => startEdit(ev)} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-accent/40 hover:text-accent transition-colors"><Pencil size={14} /></button>
                <button onClick={() => handleDelete(ev.id)} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-text-secondary hover:border-danger/40 hover:text-danger transition-colors"><Trash2 size={14} /></button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
