"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card } from "@/components/ui/card";
import { MediaPicker, MediaItem } from "@/components/admin/media-picker";
import { toast } from "sonner";
import { Loader2, Save, Trash2, Plus, X, Video, ImageIcon } from "lucide-react";

const PROJECT_CATEGORIES = ["Industrial", "Commercial", "Healthcare", "Residential", "Other"];

export type ProjectFormValues = {
  id?: string;
  title: string;
  slug: string;
  description: string;
  content: string;
  category: string;
  location: string;
  completionDate: string;
  client: string;
  images: string[];
  videos: string[];
  isFeatured: boolean;
  isEnabled: boolean;
  metaTitle: string;
  metaDescription: string;
};

export function ProjectForm({ initial, isNew }: { initial?: ProjectFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<ProjectFormValues>(
    initial || {
      title: "", slug: "", description: "", content: "", category: "Commercial",
      location: "", completionDate: "", client: "", images: [], videos: [],
      isFeatured: false, isEnabled: true, metaTitle: "", metaDescription: "",
    }
  );
  const [imagePickerOpen, setImagePickerOpen] = React.useState(false);
  const [videoPickerOpen, setVideoPickerOpen] = React.useState(false);

  const set = <K extends keyof ProjectFormValues>(k: K, v: ProjectFormValues[K]) =>
    setValues((prev) => ({ ...prev, [k]: v }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!values.title.trim()) return toast.error("Title is required");
    setLoading(true);
    try {
      const url = isNew ? "/api/admin/projects" : `/api/admin/projects/${values.id}`;
      const res = await fetch(url, {
        method: isNew ? "POST" : "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      if (!res.ok) {
        const d = await res.json();
        throw new Error(d.error || "Failed");
      }
      toast.success(isNew ? "Project created" : "Project updated");
      router.push("/admin/projects");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const onDelete = async () => {
    if (!confirm("Delete this project? This cannot be undone.")) return;
    setLoading(true);
    try {
      await fetch(`/api/admin/projects/${values.id}`, { method: "DELETE" });
      toast.success("Project deleted");
      router.push("/admin/projects");
      router.refresh();
    } catch {
      toast.error("Delete failed");
    } finally {
      setLoading(false);
    }
  };

  const addImage = (item: MediaItem) => {
    set("images", [...values.images, item.url]);
  };
  const addVideo = (item: MediaItem) => {
    set("videos", [...values.videos, item.url]);
  };

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-5">
          <Card className="p-6 rounded-2xl space-y-5">
            <h2 className="font-bold text-lg">Project Details</h2>
            <div className="space-y-1.5">
              <Label>Title *</Label>
              <Input value={values.title} onChange={(e) => {
                set("title", e.target.value);
                if (isNew) set("slug", e.target.value.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").slice(0, 80));
              }} required />
            </div>
            <div className="space-y-1.5">
              <Label>Slug</Label>
              <Input value={values.slug} onChange={(e) => set("slug", e.target.value)} placeholder="auto-generated-from-title" />
            </div>
            <div className="space-y-1.5">
              <Label>Description</Label>
              <Textarea rows={3} value={values.description} onChange={(e) => set("description", e.target.value)} />
            </div>
            <div className="space-y-1.5">
              <Label>Full Content</Label>
              <Textarea rows={8} value={values.content} onChange={(e) => set("content", e.target.value)} />
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Category</Label>
                <Select value={values.category} onValueChange={(v) => set("category", v)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {PROJECT_CATEGORIES.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label>Completion Date</Label>
                <Input type="date" value={values.completionDate} onChange={(e) => set("completionDate", e.target.value)} />
              </div>
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Location</Label>
                <Input value={values.location} onChange={(e) => set("location", e.target.value)} placeholder="e.g. Karachi, Pakistan" />
              </div>
              <div className="space-y-1.5">
                <Label>Client</Label>
                <Input value={values.client} onChange={(e) => set("client", e.target.value)} placeholder="Client name (optional)" />
              </div>
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="font-bold text-lg">Project Images</h2>
              <Button type="button" size="sm" variant="outline" onClick={() => setImagePickerOpen(true)}>
                <Plus className="size-4 mr-1.5" /> Add Image
              </Button>
            </div>
            {values.images.length === 0 ? (
              <div className="text-sm text-muted-foreground text-center py-6 rounded-lg bg-muted/40 border border-dashed">
                No images yet. Click &quot;Add Image&quot; to select from media library.
              </div>
            ) : (
              <div className="grid grid-cols-3 sm:grid-cols-4 gap-3">
                {values.images.map((url, i) => (
                  <div key={i} className="group relative aspect-square rounded-lg overflow-hidden border border-border">
                    <img src={url} alt={`Project image ${i + 1}`} className="size-full object-cover" />
                    <button
                      type="button"
                      onClick={() => set("images", values.images.filter((_, idx) => idx !== i))}
                      className="absolute top-1 right-1 grid place-items-center size-6 rounded-md bg-black/60 text-white opacity-0 group-hover:opacity-100 hover:bg-destructive transition-colors"
                    >
                      <X className="size-3.5" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </Card>

          <Card className="p-6 rounded-2xl space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="font-bold text-lg">Project Videos</h2>
              <Button type="button" size="sm" variant="outline" onClick={() => setVideoPickerOpen(true)}>
                <Plus className="size-4 mr-1.5" /> Add Video
              </Button>
            </div>
            {values.videos.length === 0 ? (
              <div className="text-sm text-muted-foreground text-center py-6 rounded-lg bg-muted/40 border border-dashed">
                No videos yet. Click &quot;Add Video&quot; to select from media library.
              </div>
            ) : (
              <div className="space-y-2">
                {values.videos.map((url, i) => (
                  <div key={i} className="flex items-center gap-3 p-2 rounded-lg bg-muted/40">
                    <div className="grid place-items-center size-10 rounded bg-black/10 shrink-0">
                      <Video className="size-5 text-muted-foreground" />
                    </div>
                    <span className="text-xs text-muted-foreground truncate flex-1">{url}</span>
                    <button
                      type="button"
                      onClick={() => set("videos", values.videos.filter((_, idx) => idx !== i))}
                      className="text-muted-foreground hover:text-destructive"
                    >
                      <X className="size-4" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </Card>

          <Card className="p-6 rounded-2xl space-y-4">
            <h2 className="font-bold text-lg">SEO Settings</h2>
            <div className="space-y-1.5">
              <Label>Meta Title</Label>
              <Input value={values.metaTitle} onChange={(e) => set("metaTitle", e.target.value)} placeholder="Defaults to project title" />
            </div>
            <div className="space-y-1.5">
              <Label>Meta Description</Label>
              <Textarea rows={2} value={values.metaDescription} onChange={(e) => set("metaDescription", e.target.value)} />
            </div>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-5">
          <Card className="p-6 rounded-2xl space-y-4">
            <h2 className="font-bold">Status</h2>
            <div className="flex items-center justify-between">
              <Label htmlFor="enabled">Enabled</Label>
              <Switch id="enabled" checked={values.isEnabled} onCheckedChange={(v) => set("isEnabled", v)} />
            </div>
            <div className="flex items-center justify-between">
              <Label htmlFor="featured">Featured Project</Label>
              <Switch id="featured" checked={values.isFeatured} onCheckedChange={(v) => set("isFeatured", v)} />
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-3">
            <h2 className="font-bold">Cover Preview</h2>
            {values.images[0] ? (
              <div className="aspect-video rounded-lg overflow-hidden border border-border">
                <img src={values.images[0]} alt="Cover" className="size-full object-cover" />
              </div>
            ) : (
              <div className="aspect-video rounded-lg bg-muted/40 border border-dashed grid place-items-center text-muted-foreground">
                <ImageIcon className="size-8" />
              </div>
            )}
            <p className="text-xs text-muted-foreground">The first image is used as the cover thumbnail.</p>
          </Card>

          <div className="flex flex-col gap-2">
            <Button type="submit" disabled={loading} className="brand-gradient text-white">
              {loading ? <Loader2 className="size-4 mr-2 animate-spin" /> : <Save className="size-4 mr-2" />}
              {isNew ? "Create Project" : "Save Changes"}
            </Button>
            <Button type="button" variant="outline" onClick={() => router.back()}>Cancel</Button>
            {!isNew && (
              <Button type="button" variant="ghost" className="text-destructive" onClick={onDelete} disabled={loading}>
                <Trash2 className="size-4 mr-2" /> Delete Project
              </Button>
            )}
          </div>
        </div>
      </div>

      <MediaPicker
        open={imagePickerOpen}
        onOpenChange={setImagePickerOpen}
        accept="image"
        onSelect={addImage}
      />
      <MediaPicker
        open={videoPickerOpen}
        onOpenChange={setVideoPickerOpen}
        accept="video"
        onSelect={addVideo}
      />
    </form>
  );
}
