"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 { Card } from "@/components/ui/card";
import { MediaPickerButton } from "@/components/admin/media-picker";
import { toast } from "sonner";
import { Loader2, Save, Trash2 } from "lucide-react";

export type BeforeAfterFormValues = {
  id?: string;
  title: string;
  description: string;
  category: string;
  location: string;
  completionDate: string;
  beforeImage: string;
  afterImage: string;
  isEnabled: boolean;
  order: number;
};

export function BeforeAfterForm({ initial, isNew }: { initial?: BeforeAfterFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<BeforeAfterFormValues>(
    initial || {
      title: "", description: "", category: "", location: "", completionDate: "",
      beforeImage: "", afterImage: "", isEnabled: true, order: 0,
    }
  );

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

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!values.title.trim()) return toast.error("Title is required");
    if (!values.beforeImage) return toast.error("Before image is required");
    if (!values.afterImage) return toast.error("After image is required");
    setLoading(true);
    try {
      const url = isNew ? "/api/admin/before-after" : `/api/admin/before-after/${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 ? "Before/After created" : "Before/After updated");
      router.push("/admin/before-after");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

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

  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">Details</h2>
            <div className="space-y-1.5">
              <Label>Title *</Label>
              <Input value={values.title} onChange={(e) => set("title", e.target.value)} required />
            </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="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Category</Label>
                <Input value={values.category} onChange={(e) => set("category", e.target.value)} placeholder="e.g. Chiller Repair" />
              </div>
              <div className="space-y-1.5">
                <Label>Location</Label>
                <Input value={values.location} onChange={(e) => set("location", e.target.value)} placeholder="e.g. Karachi" />
              </div>
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <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 className="space-y-1.5">
                <Label>Display Order</Label>
                <Input type="number" value={values.order} onChange={(e) => set("order", parseInt(e.target.value) || 0)} />
              </div>
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-4">
            <h2 className="font-bold text-lg">Images</h2>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Before Image *</Label>
                <MediaPickerButton value={values.beforeImage} onChange={(v) => set("beforeImage", v || "")} accept="image" label="Upload Before" />
              </div>
              <div className="space-y-2">
                <Label>After Image *</Label>
                <MediaPickerButton value={values.afterImage} onChange={(v) => set("afterImage", v || "")} accept="image" label="Upload After" />
              </div>
            </div>
            {values.beforeImage && values.afterImage && (
              <div className="grid grid-cols-2 gap-3 pt-2">
                <div className="space-y-1">
                  <span className="text-xs text-muted-foreground">Before preview</span>
                  <div className="aspect-video rounded-lg overflow-hidden border border-border">
                    <img src={values.beforeImage} alt="Before" className="size-full object-cover" />
                  </div>
                </div>
                <div className="space-y-1">
                  <span className="text-xs text-muted-foreground">After preview</span>
                  <div className="aspect-video rounded-lg overflow-hidden border border-border">
                    <img src={values.afterImage} alt="After" className="size-full object-cover" />
                  </div>
                </div>
              </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>
          </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 Entry" : "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 Entry
              </Button>
            )}
          </div>
        </div>
      </div>
    </form>
  );
}
