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

const ICON_OPTIONS = [
  "Wrench", "Settings", "Snowflake", "Wind", "Droplets", "GlassWater", "Refrigerator",
  "ShieldCheck", "Repeat", "Factory", "ThermometerSnowflake", "Fan", "AirVent", "Zap",
  "Building2", "Tool", "HardHat", "Flame", "Cpu", "Cloud",
];

export type ServiceFormValues = {
  id?: string;
  title: string;
  slug: string;
  shortDescription: string;
  description: string;
  icon: string;
  image: string | null;
  features: string[];
  isEnabled: boolean;
  order: number;
  metaTitle: string;
  metaDescription: string;
};

export function ServiceForm({ initial, isNew }: { initial?: ServiceFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<ServiceFormValues>(
    initial || {
      title: "", slug: "", shortDescription: "", description: "", icon: "Wrench",
      image: null, features: [], isEnabled: true, order: 0, metaTitle: "", metaDescription: "",
    }
  );
  const [newFeature, setNewFeature] = React.useState("");

  const set = <K extends keyof ServiceFormValues>(k: K, v: ServiceFormValues[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/services" : `/api/admin/services/${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 ? "Service created" : "Service updated");
      router.push("/admin/services");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const onDelete = async () => {
    if (!confirm("Delete this service? This cannot be undone.")) return;
    setLoading(true);
    try {
      await fetch(`/api/admin/services/${values.id}`, { method: "DELETE" });
      toast.success("Service deleted");
      router.push("/admin/services");
      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">Service 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>Short Description</Label>
              <Textarea rows={2} value={values.shortDescription} onChange={(e) => set("shortDescription", e.target.value)} />
            </div>
            <div className="space-y-1.5">
              <Label>Full Description</Label>
              <Textarea rows={6} 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>Icon</Label>
                <Select value={values.icon} onValueChange={(v) => set("icon", v)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {ICON_OPTIONS.map((i) => <SelectItem key={i} value={i}>{i}</SelectItem>)}
                  </SelectContent>
                </Select>
              </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-3">
            <div className="flex items-center justify-between">
              <h2 className="font-bold text-lg">Features</h2>
            </div>
            <div className="flex gap-2">
              <Input value={newFeature} onChange={(e) => setNewFeature(e.target.value)} placeholder="Add a feature..." onKeyDown={(e) => {
                if (e.key === "Enter") { e.preventDefault(); if (newFeature.trim()) { set("features", [...values.features, newFeature.trim()]); setNewFeature(""); } }
              }} />
              <Button type="button" onClick={() => { if (newFeature.trim()) { set("features", [...values.features, newFeature.trim()]); setNewFeature(""); } }}>
                <Plus className="size-4" />
              </Button>
            </div>
            <div className="space-y-2">
              {values.features.map((f, i) => (
                <div key={i} className="flex items-center justify-between gap-2 px-3 py-2 rounded-lg bg-muted/50">
                  <span className="text-sm">{f}</span>
                  <button type="button" onClick={() => set("features", values.features.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 service 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>
          </Card>
          <Card className="p-6 rounded-2xl space-y-3">
            <h2 className="font-bold">Service Image</h2>
            <MediaPickerButton value={values.image} onChange={(v) => set("image", v)} accept="image" label="Upload Image" />
          </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 Service" : "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 Service
              </Button>
            )}
          </div>
        </div>
      </div>
    </form>
  );
}
