"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 } from "lucide-react";

export type TestimonialFormValues = {
  id?: string;
  name: string;
  position: string;
  company: string;
  content: string;
  rating: number;
  avatar: string | null;
  isEnabled: boolean;
  order: number;
};

export function TestimonialForm({ initial, isNew }: { initial?: TestimonialFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<TestimonialFormValues>(
    initial || {
      name: "",
      position: "",
      company: "",
      content: "",
      rating: 5,
      avatar: null,
      isEnabled: true,
      order: 0,
    }
  );

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

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!values.name.trim()) return toast.error("Name is required");
    if (!values.content.trim()) return toast.error("Content is required");
    setLoading(true);
    try {
      const url = isNew ? "/api/admin/testimonials" : `/api/admin/testimonials/${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 ? "Testimonial created" : "Testimonial updated");
      router.push("/admin/testimonials");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const onDelete = async () => {
    if (!confirm("Delete this testimonial? This cannot be undone.")) return;
    setLoading(true);
    try {
      await fetch(`/api/admin/testimonials/${values.id}`, { method: "DELETE" });
      toast.success("Testimonial deleted");
      router.push("/admin/testimonials");
      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">Customer Details</h2>
            <div className="space-y-1.5">
              <Label>Name *</Label>
              <Input
                value={values.name}
                onChange={(e) => set("name", e.target.value)}
                placeholder="e.g. Ahmed Khan"
                required
              />
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Position</Label>
                <Input
                  value={values.position}
                  onChange={(e) => set("position", e.target.value)}
                  placeholder="e.g. Facility Manager"
                />
              </div>
              <div className="space-y-1.5">
                <Label>Company</Label>
                <Input
                  value={values.company}
                  onChange={(e) => set("company", e.target.value)}
                  placeholder="e.g. XYZ Textiles"
                />
              </div>
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-5">
            <h2 className="font-bold text-lg">Testimonial</h2>
            <div className="space-y-1.5">
              <Label>Content *</Label>
              <Textarea
                rows={5}
                value={values.content}
                onChange={(e) => set("content", e.target.value)}
                placeholder="What did the customer say about AHE Services?"
                required
              />
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Rating</Label>
                <Select value={String(values.rating)} onValueChange={(v) => set("rating", parseInt(v))}>
                  <SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {[5, 4, 3, 2, 1].map((r) => (
                      <SelectItem key={r} value={String(r)}>
                        {r} Star{r > 1 ? "s" : ""}
                      </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>
        </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">Customer Avatar</h2>
            <MediaPickerButton value={values.avatar} onChange={(v) => set("avatar", v)} accept="image" label="Upload Avatar" />
          </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 Testimonial" : "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 Testimonial
              </Button>
            )}
          </div>
        </div>
      </div>
    </form>
  );
}
