"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createProject, updateProject } from "@/lib/actions/project";
import {
  Save,
  ChevronLeft,
  Briefcase,
  Layers,
  Link as LinkIcon,
  Github,
  Award,
  Trash2,
  Plus,
  X,
} from "lucide-react";
import Link from "next/link";
import { cn } from "@/lib/utils";

interface ProjectFormProps {
  initialData?: any;
}

export function ProjectForm({ initialData }: ProjectFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [techStack, setTechStack] = useState<string[]>(
    initialData?.techStack || [],
  );
  const [techInput, setTechInput] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);

    try {
      const formData = new FormData(e.currentTarget);
      const data = {
        title: formData.get("title") as string,
        description: formData.get("description") as string,
        imageUrl: formData.get("imageUrl") as string || null,
        liveUrl: formData.get("liveUrl") as string || null,
        githubUrl: formData.get("githubUrl") as string || null,
        techStack: techStack,
        featured: formData.get("featured") === "on",
        order: parseInt(formData.get("order") as string) || 0,
      };

      if (initialData) {
        await updateProject(initialData.id, data);
      } else {
        await createProject(data);
      }

      router.push("/dashboard/projects");
      router.refresh();
    } catch (error) {
      console.error(error);
      alert("Something went wrong.");
    } finally {
      setLoading(false);
    }
  }

  const addTech = () => {
    if (techInput && !techStack.includes(techInput)) {
      setTechStack([...techStack, techInput]);
      setTechInput("");
    }
  };

  const removeTech = (tech: string) => {
    setTechStack(techStack.filter((t) => t !== tech));
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-8 max-w-5xl mx-auto pb-20">
      <div className="flex items-center justify-between gap-4 border-b border-border pb-6">
        <div className="flex items-center gap-4">
          <Link
            href="/dashboard/projects"
            className="p-2 hover:bg-surface-elevated rounded-lg text-foreground-muted transition-colors"
          >
            <ChevronLeft size={20} />
          </Link>
          <div>
            <h1 className="text-2xl font-display font-bold text-foreground">
              {initialData ? "Edit Project" : "New Portfolio Project"}
            </h1>
            <p className="text-sm text-foreground-muted">
              {initialData ? "Refine your project details." : "Add a new achievement to your collection."}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button
            type="button"
            onClick={() => router.back()}
            className="px-4 py-2 border border-border bg-surface text-foreground font-medium rounded-lg hover:bg-surface-elevated transition-all text-sm"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={loading}
            className="inline-flex items-center gap-2 px-6 py-2 bg-primary text-primary-foreground font-semibold rounded-lg hover:shadow-lg hover:shadow-primary/20 transition-all disabled:opacity-50 text-sm"
          >
            <Save size={18} />
            {loading ? "Saving..." : initialData ? "Update Project" : "Create Project"}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-6 card-shadow">
            <div className="space-y-4">
              <div className="space-y-2">
                <label className="text-sm font-semibold text-foreground flex items-center gap-2">
                   <Briefcase size={16} className="text-primary/60" />
                   Project Title
                </label>
                <input
                  name="title"
                  defaultValue={initialData?.title}
                  placeholder="e.g. Finance Hub Pro"
                  required
                  className="w-full px-4 py-2.5 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-sm font-medium"
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-semibold text-foreground">Detailed Description</label>
                <textarea
                  name="description"
                  defaultValue={initialData?.description}
                  placeholder="Describe your project, your role, and the value it provided..."
                  required
                  rows={8}
                  className="w-full px-4 py-3 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all text-sm leading-relaxed"
                />
              </div>
            </div>
          </div>

          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-6 card-shadow">
             <h3 className="text-sm font-bold uppercase tracking-widest text-foreground-muted">Assets & Visibility</h3>
             
             <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-semibold text-foreground">Thumbnail Image URL</label>
                  <input
                    name="imageUrl"
                    defaultValue={initialData?.imageUrl}
                    placeholder="https://..."
                    className="w-full px-4 py-2 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm"
                  />
                </div>
                 <div className="space-y-2">
                  <label className="text-sm font-semibold text-foreground">Display Order</label>
                  <input
                    name="order"
                    type="number"
                    defaultValue={initialData?.order || 0}
                    className="w-full px-4 py-2 bg-background border border-border/50 rounded-xl focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm"
                  />
                </div>
             </div>

             <div className="flex items-center gap-2 pt-4 border-t border-border/50">
               <input
                 name="featured"
                 type="checkbox"
                 id="featured"
                 defaultChecked={initialData?.featured}
                 className="w-4 h-4 rounded border-border text-primary focus:ring-primary"
               />
               <label htmlFor="featured" className="text-sm font-medium text-foreground flex items-center gap-1.5 cursor-pointer">
                 <Award size={14} className="text-yellow-500" />
                 Feature this project on homepage
               </label>
             </div>
          </div>
        </div>

        <div className="space-y-6">
          {/* Links Section */}
          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-4 card-shadow">
            <h3 className="text-sm font-bold uppercase tracking-widest text-foreground-muted">Project Links</h3>
            
            <div className="space-y-4">
               <div className="space-y-2">
                <label className="text-xs font-semibold text-foreground flex items-center gap-2">
                  <LinkIcon size={14} />
                  Live Preview URL
                </label>
                <input
                  name="liveUrl"
                  defaultValue={initialData?.liveUrl}
                  placeholder="https://example.com"
                  className="w-full px-3 py-2 bg-background border border-border/50 rounded-lg focus:ring-2 focus:ring-primary/20 outline-none transition-all text-xs"
                />
              </div>

               <div className="space-y-2">
                <label className="text-xs font-semibold text-foreground flex items-center gap-2">
                  <Github size={14} />
                  Github Repository
                </label>
                <input
                  name="githubUrl"
                  defaultValue={initialData?.githubUrl}
                  placeholder="https://github.com/..."
                  className="w-full px-3 py-2 bg-background border border-border/50 rounded-lg focus:ring-2 focus:ring-primary/20 outline-none transition-all text-xs"
                />
              </div>
            </div>
          </div>

          {/* Tech Stack */}
          <div className="bg-surface border border-border/50 rounded-2xl p-6 space-y-4 card-shadow">
             <h3 className="text-sm font-bold uppercase tracking-widest text-foreground-muted flex items-center gap-2">
              <Layers size={14} />
              Tech Stack
            </h3>
            
            <div className="flex gap-2">
              <input
                value={techInput}
                onChange={(e) => setTechInput(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addTech())}
                placeholder="Add tech..."
                className="flex-1 px-3 py-2 bg-background border border-border/50 rounded-lg text-xs outline-none focus:border-primary"
              />
              <button
                type="button"
                onClick={addTech}
                className="p-2 bg-primary/10 text-primary rounded-lg hover:bg-primary/20 transition-colors"
              >
                <Plus size={16} />
              </button>
            </div>

            <div className="flex flex-wrap gap-2 pt-2">
              {techStack.map((tech) => (
                <span
                  key={tech}
                  className="inline-flex items-center gap-1 px-2 py-1 bg-surface-elevated border border-border/50 rounded-md text-[10px] font-bold text-foreground"
                >
                  {tech}
                  <button
                    type="button"
                    onClick={() => removeTech(tech)}
                    className="p-0.5 hover:text-destructive transition-colors"
                  >
                    <X size={10} />
                  </button>
                </span>
              ))}
              {techStack.length === 0 && (
                <p className="text-xs text-foreground-muted italic text-center w-full">No technologies listed.</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}
