"use client";

import { useEffect, useState } from "react";
import { Loader2, Plus, Save, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { ImageUrlField } from "@/components/admin/image-url-field";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { formatInr } from "@/lib/format/inr";
import type { CmsFaqItem, CmsProduct, CmsTestimonial, CmsTransformation } from "@/lib/cms/types";

export function CmsContentManager() {
  const [faq, setFaq] = useState<CmsFaqItem[]>([]);
  const [testimonials, setTestimonials] = useState<CmsTestimonial[]>([]);
  const [transformations, setTransformations] = useState<CmsTransformation[]>([]);
  const [products, setProducts] = useState<CmsProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    async function loadInitial() {
      const [faqRes, testRes, transRes, prodRes] = await Promise.all([
        fetch("/api/admin/cms/faq"),
        fetch("/api/admin/cms/testimonials"),
        fetch("/api/admin/cms/transformations"),
        fetch("/api/admin/cms/products"),
      ]);
      if (cancelled) return;
      if (faqRes.ok) setFaq(((await faqRes.json()) as { items: CmsFaqItem[] }).items ?? []);
      if (testRes.ok) setTestimonials(((await testRes.json()) as { items: CmsTestimonial[] }).items ?? []);
      if (transRes.ok) setTransformations(((await transRes.json()) as { items: CmsTransformation[] }).items ?? []);
      if (prodRes.ok) setProducts(((await prodRes.json()) as { items: CmsProduct[] }).items ?? []);
      setLoading(false);
    }
    void loadInitial().catch(() => {
      if (!cancelled) setLoading(false);
    });
    return () => {
      cancelled = true;
    };
  }, []);

  async function saveFaq() {
    setSaving("faq");
    const res = await fetch("/api/admin/cms/faq", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ items: faq.map((item, i) => ({ ...item, position: i })) }),
    });
    setSaving(null);
    toast[res.ok ? "success" : "error"](res.ok ? "FAQ saved." : "Save failed.");
  }

  async function saveTestimonials() {
    setSaving("testimonials");
    const res = await fetch("/api/admin/cms/testimonials", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ items: testimonials.map((item, i) => ({ ...item, position: i })) }),
    });
    setSaving(null);
    toast[res.ok ? "success" : "error"](res.ok ? "Testimonials saved." : "Save failed.");
  }

  async function saveTransformations() {
    setSaving("transformations");
    const res = await fetch("/api/admin/cms/transformations", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ items: transformations.map((item, i) => ({ ...item, position: i })) }),
    });
    setSaving(null);
    toast[res.ok ? "success" : "error"](res.ok ? "Gallery saved." : "Save failed.");
  }

  async function saveProduct(item: CmsProduct) {
    setSaving(item.id);
    const res = await fetch("/api/admin/cms/products", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(item),
    });
    setSaving(null);
    toast[res.ok ? "success" : "error"](res.ok ? "Plan saved." : "Save failed.");
  }

  if (loading) {
    return (
      <div className="text-muted-foreground flex items-center gap-2 py-12">
        <Loader2 className="size-5 animate-spin text-primary" /> Loading…
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-display text-2xl font-semibold">Content</h1>
        <p className="text-muted-foreground mt-1 text-sm">
          Edit text and images for plans, FAQ, testimonials, and the transformation gallery.
        </p>
      </div>

      <Tabs defaultValue="plans">
        <TabsList className="flex-wrap">
          <TabsTrigger value="plans">Plans & pricing</TabsTrigger>
          <TabsTrigger value="faq">FAQ</TabsTrigger>
          <TabsTrigger value="testimonials">Testimonials</TabsTrigger>
          <TabsTrigger value="transformations">Gallery</TabsTrigger>
        </TabsList>

        <TabsContent value="plans" className="mt-6 space-y-4">
          {products.map((item) => (
            <div key={item.id} className="rounded-xl border border-white/10 bg-white/[0.02] p-5">
              <div className="mb-4 flex items-center justify-between gap-2">
                <span className="text-sm font-medium">
                  {item.title} · {formatInr(item.priceInr)}
                </span>
                <Button type="button" size="sm" disabled={saving === item.id} onClick={() => void saveProduct(item)}>
                  {saving === item.id ? <Loader2 className="size-4 animate-spin" /> : <Save className="size-4" />}
                </Button>
              </div>
              <div className="grid gap-4">
                <div className="space-y-2">
                  <Label>Title</Label>
                  <Input
                    value={item.title}
                    onChange={(e) =>
                      setProducts((list) => list.map((x) => (x.id === item.id ? { ...x, title: e.target.value } : x)))
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label>Description</Label>
                  <Textarea
                    rows={3}
                    value={item.description}
                    onChange={(e) =>
                      setProducts((list) =>
                        list.map((x) => (x.id === item.id ? { ...x, description: e.target.value } : x)),
                      )
                    }
                  />
                </div>
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label>Price (INR)</Label>
                    <Input
                      type="number"
                      value={item.priceInr}
                      onChange={(e) =>
                        setProducts((list) =>
                          list.map((x) =>
                            x.id === item.id ? { ...x, priceInr: Number(e.target.value) } : x,
                          ),
                        )
                      }
                    />
                  </div>
                </div>
                <ImageUrlField
                  label="Plan photo"
                  value={item.image}
                  onChange={(url) =>
                    setProducts((list) => list.map((x) => (x.id === item.id ? { ...x, image: url } : x)))
                  }
                />
                <div className="space-y-2">
                  <Label>Features (one per line)</Label>
                  <Textarea
                    rows={4}
                    value={item.features.join("\n")}
                    onChange={(e) =>
                      setProducts((list) =>
                        list.map((x) =>
                          x.id === item.id
                            ? { ...x, features: e.target.value.split("\n").filter(Boolean) }
                            : x,
                        ),
                      )
                    }
                  />
                </div>
              </div>
            </div>
          ))}
        </TabsContent>

        <TabsContent value="faq" className="mt-6 space-y-4">
          {faq.map((item) => (
            <div key={item.id} className="space-y-3 rounded-xl border border-white/10 bg-white/[0.02] p-4">
              <Input
                value={item.question}
                onChange={(e) =>
                  setFaq((items) => items.map((x) => (x.id === item.id ? { ...x, question: e.target.value } : x)))
                }
                placeholder="Question"
              />
              <Textarea
                rows={3}
                value={item.answer}
                onChange={(e) =>
                  setFaq((items) => items.map((x) => (x.id === item.id ? { ...x, answer: e.target.value } : x)))
                }
                placeholder="Answer"
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => setFaq((items) => items.filter((x) => x.id !== item.id))}
              >
                <Trash2 className="size-4" /> Remove
              </Button>
            </div>
          ))}
          <div className="flex gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() =>
                setFaq((items) => [
                  ...items,
                  { id: crypto.randomUUID(), question: "", answer: "", position: items.length, enabled: true },
                ])
              }
            >
              <Plus className="size-4" /> Add FAQ
            </Button>
            <Button disabled={saving === "faq"} onClick={() => void saveFaq()}>
              Save FAQ
            </Button>
          </div>
        </TabsContent>

        <TabsContent value="testimonials" className="mt-6 space-y-4">
          {testimonials.map((item) => (
            <div key={item.id} className="space-y-3 rounded-xl border border-white/10 bg-white/[0.02] p-4">
              <div className="grid gap-3 sm:grid-cols-2">
                <Input
                  value={item.name}
                  placeholder="Name"
                  onChange={(e) =>
                    setTestimonials((items) =>
                      items.map((x) => (x.id === item.id ? { ...x, name: e.target.value } : x)),
                    )
                  }
                />
                <Input
                  value={item.role}
                  placeholder="Role"
                  onChange={(e) =>
                    setTestimonials((items) =>
                      items.map((x) => (x.id === item.id ? { ...x, role: e.target.value } : x)),
                    )
                  }
                />
              </div>
              <Textarea
                rows={2}
                value={item.quote}
                placeholder="Quote"
                onChange={(e) =>
                  setTestimonials((items) =>
                    items.map((x) => (x.id === item.id ? { ...x, quote: e.target.value } : x)),
                  )
                }
              />
              <Input
                value={item.result}
                placeholder="Result line"
                onChange={(e) =>
                  setTestimonials((items) =>
                    items.map((x) => (x.id === item.id ? { ...x, result: e.target.value } : x)),
                  )
                }
              />
              <ImageUrlField
                label="Photo"
                value={item.image}
                onChange={(url) =>
                  setTestimonials((items) =>
                    items.map((x) => (x.id === item.id ? { ...x, image: url } : x)),
                  )
                }
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => setTestimonials((items) => items.filter((x) => x.id !== item.id))}
              >
                <Trash2 className="size-4" /> Remove
              </Button>
            </div>
          ))}
          <div className="flex gap-2">
            <Button
              variant="outline"
              onClick={() =>
                setTestimonials((items) => [
                  ...items,
                  {
                    id: crypto.randomUUID(),
                    name: "",
                    role: "",
                    quote: "",
                    result: "",
                    image: "",
                    position: items.length,
                    enabled: true,
                  },
                ])
              }
            >
              <Plus className="size-4" /> Add
            </Button>
            <Button disabled={saving === "testimonials"} onClick={() => void saveTestimonials()}>
              Save testimonials
            </Button>
          </div>
        </TabsContent>

        <TabsContent value="transformations" className="mt-6 space-y-4">
          <p className="text-muted-foreground text-sm">
            {transformations.length} gallery items. Upload images in Media, paste URL into collage field.
          </p>
          <div className="max-h-[min(70vh,640px)] space-y-3 overflow-y-auto pr-1">
          {transformations.map((item) => (
            <div key={item.id} className="space-y-3 rounded-xl border border-white/10 bg-white/[0.02] p-4">
              <div className="grid gap-3 sm:grid-cols-2">
                <Input
                  value={item.title}
                  placeholder="Title"
                  onChange={(e) =>
                    setTransformations((items) =>
                      items.map((x) => (x.id === item.id ? { ...x, title: e.target.value } : x)),
                    )
                  }
                />
                <Input
                  value={item.timeframe}
                  placeholder="Timeframe"
                  onChange={(e) =>
                    setTransformations((items) =>
                      items.map((x) => (x.id === item.id ? { ...x, timeframe: e.target.value } : x)),
                    )
                  }
                />
              </div>
              <ImageUrlField
                label="Collage image"
                value={item.collageSrc ?? ""}
                onChange={(url) =>
                  setTransformations((items) =>
                    items.map((x) => (x.id === item.id ? { ...x, collageSrc: url } : x)),
                  )
                }
              />
            </div>
          ))}
          </div>
          <Button disabled={saving === "transformations"} onClick={() => void saveTransformations()}>
            Save gallery ({transformations.length})
          </Button>
        </TabsContent>
      </Tabs>
    </div>
  );
}
