import { createFileRoute } from "@tanstack/react-router";
import { useCallback, useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "sonner";
import { Plus, Search, Trash2 } from "lucide-react";
import { kes } from "@/lib/portal";

export const Route = createFileRoute("/admin/catalog")({ component: CatalogAdmin });

type Service = {
  id: string;
  slug: string;
  name: string;
  icon: string;
  category: string;
  price_label: string;
  base_price: number;
  turnaround: string;
  description: string;
  requirements: string[];
  is_featured: boolean;
  is_active: boolean;
  sort_order: number;
};

const blank = {
  name: "",
  slug: "",
  category: "General",
  base_price: "",
  price_label: "",
  turnaround: "",
  description: "",
  requirements: "",
};

function CatalogAdmin() {
  const [rows, setRows] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [q, setQ] = useState("");
  const [form, setForm] = useState(blank);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    const { data, error } = await supabase
      .from("catalog_services")
      .select("id, slug, name, icon, category, price_label, base_price, turnaround, description, requirements, is_featured, is_active, sort_order")
      .order("sort_order")
      .order("name");
    if (error) toast.error(error.message);
    setRows((data ?? []) as Service[]);
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const patch = async (id: string, values: Partial<Service>) => {
    const { error } = await supabase.from("catalog_services").update(values).eq("id", id);
    if (error) return toast.error(error.message);
    setRows((r) => r.map((s) => (s.id === id ? { ...s, ...values } : s)));
    toast.success("Saved");
  };

  const remove = async (s: Service) => {
    if (!confirm(`Delete "${s.name}" from the catalogue?`)) return;
    const { error } = await supabase.from("catalog_services").delete().eq("id", s.id);
    if (error) return toast.error(error.message);
    setRows((r) => r.filter((x) => x.id !== s.id));
    toast.success("Service removed");
  };

  const create = async () => {
    const name = form.name.trim();
    if (!name) return toast.error("Enter a service name");
    const slug = (form.slug.trim() || name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""));
    const price = Number(form.base_price || 0);
    setSaving(true);
    const { error } = await supabase.from("catalog_services").insert({
      name,
      slug,
      category: form.category.trim() || "General",
      icon: "FileText",
      base_price: price,
      price_label: form.price_label.trim() || (price > 0 ? `From KSh ${price}` : "On request"),
      turnaround: form.turnaround.trim() || "Same day",
      description: form.description.trim() || name,
      requirements: form.requirements
        .split("\n")
        .map((r) => r.trim())
        .filter(Boolean),
      sort_order: rows.length + 1,
    });
    setSaving(false);
    if (error) return toast.error(error.message);
    toast.success("Service added");
    setForm(blank);
    load();
  };

  const term = q.trim().toLowerCase();
  const visible = rows.filter((s) => !term || `${s.name} ${s.category} ${s.slug}`.toLowerCase().includes(term));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Service catalogue</h1>
        <p className="text-sm text-muted-foreground">Add services, change prices and turnaround, and control what customers can order.</p>
      </div>

      <Card className="glass">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Plus className="h-4 w-4 text-primary" /> Add a service
          </CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 sm:grid-cols-2">
          <div className="space-y-1">
            <Label className="text-xs">Name</Label>
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="e.g. KRA PIN Registration" />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">Category</Label>
            <Input value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} placeholder="e.g. Government" />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">Base price (KSh)</Label>
            <Input type="number" min="0" value={form.base_price} onChange={(e) => setForm({ ...form, base_price: e.target.value })} placeholder="e.g. 300" />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">Turnaround</Label>
            <Input value={form.turnaround} onChange={(e) => setForm({ ...form, turnaround: e.target.value })} placeholder="e.g. 30 minutes" />
          </div>
          <div className="space-y-1 sm:col-span-2">
            <Label className="text-xs">Description</Label>
            <Textarea rows={2} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </div>
          <div className="space-y-1 sm:col-span-2">
            <Label className="text-xs">Requirements (one per line)</Label>
            <Textarea rows={3} value={form.requirements} onChange={(e) => setForm({ ...form, requirements: e.target.value })} placeholder={"National ID number\nPhone number"} />
          </div>
          <div className="sm:col-span-2">
            <Button onClick={create} disabled={saving}>
              {saving ? "Adding…" : "Add service"}
            </Button>
          </div>
        </CardContent>
      </Card>

      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input className="pl-9" placeholder="Search catalogue" value={q} onChange={(e) => setQ(e.target.value)} />
      </div>

      {loading ? (
        <div className="grid gap-2">
          {[0, 1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-20 w-full rounded-xl" />
          ))}
        </div>
      ) : (
        <div className="grid gap-2">
          {visible.length === 0 && <p className="text-sm text-muted-foreground">No services found.</p>}
          {visible.map((s) => (
            <ServiceRow key={s.id} service={s} onPatch={patch} onRemove={remove} />
          ))}
        </div>
      )}
    </div>
  );
}

function ServiceRow({
  service,
  onPatch,
  onRemove,
}: {
  service: Service;
  onPatch: (id: string, values: Partial<Service>) => void;
  onRemove: (s: Service) => void;
}) {
  const [price, setPrice] = useState(String(service.base_price ?? 0));
  const [turnaround, setTurnaround] = useState(service.turnaround ?? "");

  return (
    <Card className="glass">
      <CardContent className="grid gap-3 p-4 lg:grid-cols-[minmax(0,1.4fr)_auto] lg:items-center">
        <div className="min-w-0">
          <div className="flex flex-wrap items-center gap-2">
            <span className="truncate font-semibold">{service.name}</span>
            <Badge variant="outline" className="text-[10px]">
              {service.category}
            </Badge>
            {service.is_featured && <Badge className="text-[10px]">Featured</Badge>}
          </div>
          <div className="truncate text-xs text-muted-foreground">
            /{service.slug} · {kes(service.base_price)} · {service.turnaround}
          </div>
        </div>
        <div className="flex flex-wrap items-end gap-2">
          <div className="space-y-1">
            <Label className="text-[10px] text-muted-foreground">Price (KSh)</Label>
            <Input className="h-9 w-28" type="number" min="0" value={price} onChange={(e) => setPrice(e.target.value)} />
          </div>
          <div className="space-y-1">
            <Label className="text-[10px] text-muted-foreground">Turnaround</Label>
            <Input className="h-9 w-36" value={turnaround} onChange={(e) => setTurnaround(e.target.value)} />
          </div>
          <Button
            size="sm"
            variant="outline"
            onClick={() =>
              onPatch(service.id, {
                base_price: Number(price || 0),
                price_label: Number(price || 0) > 0 ? `From KSh ${Number(price || 0)}` : "On request",
                turnaround: turnaround.trim() || service.turnaround,
              })
            }
          >
            Save
          </Button>
          <label className="flex items-center gap-2 text-xs">
            <Switch checked={service.is_active} onCheckedChange={(v) => onPatch(service.id, { is_active: v })} />
            Available
          </label>
          <label className="flex items-center gap-2 text-xs">
            <Switch checked={service.is_featured} onCheckedChange={(v) => onPatch(service.id, { is_featured: v })} />
            Featured
          </label>
          <Button size="sm" variant="ghost" className="text-destructive" onClick={() => onRemove(service)}>
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
