"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 { toast } from "sonner";
import { Loader2, Save, Trash2 } from "lucide-react";

export type FaqFormValues = {
  id?: string;
  question: string;
  answer: string;
  category: string;
  order: number;
  isEnabled: boolean;
};

export function FaqForm({ initial, isNew }: { initial?: FaqFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<FaqFormValues>(
    initial || {
      question: "",
      answer: "",
      category: "",
      order: 0,
      isEnabled: true,
    }
  );

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

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

  const onDelete = async () => {
    if (!confirm("Delete this FAQ? This cannot be undone.")) return;
    setLoading(true);
    try {
      await fetch(`/api/admin/faq/${values.id}`, { method: "DELETE" });
      toast.success("FAQ deleted");
      router.push("/admin/faq");
      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">FAQ Details</h2>
            <div className="space-y-1.5">
              <Label>Question *</Label>
              <Input
                value={values.question}
                onChange={(e) => set("question", e.target.value)}
                placeholder="e.g. What areas do you serve?"
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label>Answer *</Label>
              <Textarea
                rows={5}
                value={values.answer}
                onChange={(e) => set("answer", e.target.value)}
                placeholder="Provide a clear, helpful answer..."
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label>Category</Label>
              <Input
                value={values.category}
                onChange={(e) => set("category", e.target.value)}
                placeholder="e.g. Services, Pricing, AMC (optional)"
              />
              <p className="text-xs text-muted-foreground">Used to group FAQs on the public FAQ page.</p>
            </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="space-y-1.5">
              <Label>Display Order</Label>
              <Input
                type="number"
                value={values.order}
                onChange={(e) => set("order", parseInt(e.target.value) || 0)}
              />
              <p className="text-xs text-muted-foreground">Lower numbers appear first.</p>
            </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 FAQ" : "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 FAQ
              </Button>
            )}
          </div>
        </div>
      </div>
    </form>
  );
}
