"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2, Save, Plus, X } from "lucide-react";
import { RichTextEditor } from "@/components/admin/RichTextEditor";
import { ImageUpload } from "@/components/admin/ImageUpload";
import { slugify } from "@/lib/types";

const PROJECT_TYPES = [
  { value: "product", label: "محصول" },
  { value: "brand-system", label: "سیستم برند" },
  { value: "open-source", label: "اوپن سورس" },
  { value: "creative-work", label: "کار خلاقانه" },
];

interface ProjectFormData {
  id?: string;
  title: string;
  slug: string;
  locale: string;
  projectType: string;
  description: string;
  body: string;
  coverImage: string;
  gallery: string[];
  techStack: string[];
  toolsUsed: string[];
  liveUrl: string;
  githubUrl: string;
  featured: boolean;
  sortOrder: number;
  seoTitle: string;
  seoDesc: string;
}

interface Props { initialData?: Partial<ProjectFormData> }

export function ProjectForm({ initialData }: Props) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [newTech, setNewTech] = useState("");
  const [newTool, setNewTool] = useState("");

  const [form, setForm] = useState<ProjectFormData>({
    title: "", slug: "", locale: "fa", projectType: "product",
    description: "", body: "", coverImage: "", gallery: [],
    techStack: [], toolsUsed: [], liveUrl: "", githubUrl: "",
    featured: false, sortOrder: 0, seoTitle: "", seoDesc: "",
    ...initialData,
  });

  function set(key: keyof ProjectFormData, value: unknown) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title || !form.slug) { setError("عنوان و اسلاگ الزامی است"); return; }
    setError(null); setSaving(true);
    try {
      const method = initialData?.id ? "PUT" : "POST";
      const url = initialData?.id ? `/api/admin/projects/${initialData.id}` : "/api/admin/projects";
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          gallery: JSON.stringify(form.gallery),
          techStack: JSON.stringify(form.techStack),
          toolsUsed: JSON.stringify(form.toolsUsed),
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Save failed");
      setSuccess(true);
      setTimeout(() => router.push("/admin/projects"), 800);
    } catch (e) { setError(e instanceof Error ? e.message : "خطا در ذخیره"); }
    finally { setSaving(false); }
  }

  function addToArray(key: "techStack" | "toolsUsed", val: string) {
    if (val.trim() && !form[key].includes(val.trim())) {
      set(key, [...form[key], val.trim()]);
    }
  }
  function removeFromArray(key: "techStack" | "toolsUsed", val: string) {
    set(key, form[key].filter((v) => v !== val));
  }

  return (
    <form onSubmit={handleSave} className="space-y-8">
      {error && <div className="rounded-lg border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{error}</div>}
      {success && <div className="rounded-lg border border-success/30 bg-success/10 px-4 py-3 text-sm text-success">ذخیره شد ✓</div>}

      <div className="rounded-xl border border-border bg-surface p-6 space-y-4">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">اطلاعات اصلی</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-text-primary mb-1.5">عنوان *</label>
            <input type="text" value={form.title} onChange={(e) => { set("title", e.target.value); if (!initialData?.id) set("slug", slugify(e.target.value)); }} required className="admin-input w-full" />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">اسلاگ *</label>
            <input type="text" value={form.slug} onChange={(e) => set("slug", e.target.value)} required dir="ltr" className="admin-input w-full font-mono text-sm" />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">زبان</label>
            <select value={form.locale} onChange={(e) => set("locale", e.target.value)} className="admin-input w-full">
              <option value="fa">فارسی</option>
              <option value="en">English</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">نوع پروژه</label>
            <select value={form.projectType} onChange={(e) => set("projectType", e.target.value)} className="admin-input w-full">
              {PROJECT_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">ترتیب نمایش</label>
            <input type="number" value={form.sortOrder} onChange={(e) => set("sortOrder", parseInt(e.target.value) || 0)} className="admin-input w-full" />
          </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) => set("description", e.target.value)} rows={2} className="admin-input w-full resize-none" />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">لینک زنده</label>
            <input type="url" value={form.liveUrl} onChange={(e) => set("liveUrl", e.target.value)} dir="ltr" className="admin-input w-full" placeholder="https://..." />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">لینک GitHub</label>
            <input type="url" value={form.githubUrl} onChange={(e) => set("githubUrl", e.target.value)} dir="ltr" className="admin-input w-full" placeholder="https://github.com/..." />
          </div>
        </div>
        <div className="flex items-center gap-3">
          <input type="checkbox" id="featured-project" checked={form.featured} onChange={(e) => set("featured", e.target.checked)} className="h-4 w-4 rounded border-border accent-accent" />
          <label htmlFor="featured-project" className="text-sm text-text-primary">پروژه ویژه (Featured)</label>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-surface p-6 space-y-3">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">تصویر کاور</h2>
        <ImageUpload value={form.coverImage} onChange={(url) => set("coverImage", url)} />
      </div>

      {/* Tech stack */}
      <div className="rounded-xl border border-border bg-surface p-6 space-y-4">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">تکنولوژی‌ها و ابزارها</h2>
        <div>
          <label className="block text-sm font-medium text-text-primary mb-2">تکنولوژی‌ها</label>
          <div className="flex flex-wrap gap-2 mb-2">
            {form.techStack.map((t) => (
              <span key={t} className="flex items-center gap-1 rounded-full border border-border bg-surface-hover px-2.5 py-1 text-xs text-text-secondary">
                {t} <button type="button" onClick={() => removeFromArray("techStack", t)}><X size={10} /></button>
              </span>
            ))}
          </div>
          <div className="flex gap-2">
            <input type="text" value={newTech} onChange={(e) => setNewTech(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addToArray("techStack", newTech); setNewTech(""); } }} placeholder="مثلاً: Next.js + Enter" className="admin-input flex-1" dir="ltr" />
            <button type="button" onClick={() => { addToArray("techStack", newTech); setNewTech(""); }} className="flex items-center gap-1 rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:text-text-primary transition-colors">
              <Plus size={14} />
            </button>
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-text-primary mb-2">ابزارها</label>
          <div className="flex flex-wrap gap-2 mb-2">
            {form.toolsUsed.map((t) => (
              <span key={t} className="flex items-center gap-1 rounded-full border border-border bg-surface-hover px-2.5 py-1 text-xs text-text-secondary">
                {t} <button type="button" onClick={() => removeFromArray("toolsUsed", t)}><X size={10} /></button>
              </span>
            ))}
          </div>
          <div className="flex gap-2">
            <input type="text" value={newTool} onChange={(e) => setNewTool(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addToArray("toolsUsed", newTool); setNewTool(""); } }} placeholder="مثلاً: Figma + Enter" className="admin-input flex-1" dir="ltr" />
            <button type="button" onClick={() => { addToArray("toolsUsed", newTool); setNewTool(""); }} className="flex items-center gap-1 rounded-lg border border-border px-3 py-2 text-sm text-text-secondary hover:text-text-primary transition-colors">
              <Plus size={14} />
            </button>
          </div>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-surface p-6 space-y-3">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">محتوا</h2>
        <RichTextEditor value={form.body} onChange={(html) => set("body", html)} placeholder="توضیحات کامل پروژه..." />
      </div>

      <div className="flex items-center gap-3 justify-end">
        <button type="submit" disabled={saving} className="flex items-center gap-2 rounded-lg bg-accent px-5 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} />}
          {initialData?.id ? "ذخیره تغییرات" : "ایجاد پروژه"}
        </button>
      </div>
    </form>
  );
}
