import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useState } from "react";
import { Plus, Pencil, Trash2, Star, EyeOff, Eye, X } from "lucide-react";
import { formatPrice } from "@/lib/format";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/services")({
  component: ServicesAdmin,
});

type Service = {
  id?: string;
  category_id: string | null;
  name: string;
  tagline: string | null;
  description: string | null;
  price_cents: number;
  price_suffix: string | null;
  features: string[];
  ideal_for: string[];
  featured: boolean;
  published: boolean;
  sort_order: number;
};

const empty: Service = {
  category_id: null, name: "", tagline: "", description: "",
  price_cents: 0, price_suffix: "", features: [], ideal_for: [],
  featured: false, published: true, sort_order: 0,
};

function ServicesAdmin() {
  const qc = useQueryClient();
  const [editing, setEditing] = useState<Service | null>(null);

  const { data } = useQuery({
    queryKey: ["admin-services"],
    queryFn: async () => {
      const [s, c] = await Promise.all([
        supabase.from("services").select("*").order("sort_order"),
        supabase.from("service_categories").select("*").order("sort_order"),
      ]);
      return { services: (s.data ?? []) as Service[], categories: c.data ?? [] };
    },
  });

  const save = useMutation({
    mutationFn: async (s: Service) => {
      const payload = { ...s, tagline: s.tagline || null, description: s.description || null, price_suffix: s.price_suffix || null };
      if (s.id) {
        const { error } = await supabase.from("services").update(payload).eq("id", s.id);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("services").insert(payload);
        if (error) throw error;
      }
    },
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admin-services"] }); qc.invalidateQueries({ queryKey: ["catalog"] }); setEditing(null); toast.success("Enregistré"); },
    onError: (e: any) => toast.error(e.message),
  });

  const del = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("services").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admin-services"] }); qc.invalidateQueries({ queryKey: ["catalog"] }); toast.success("Supprimé"); },
  });

  return (
    <div className="p-8">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="font-display text-3xl font-bold">Prestations</h1>
          <p className="text-sm text-muted-foreground mt-1">Gérez votre catalogue de services.</p>
        </div>
        <button onClick={() => setEditing({ ...empty })} className="inline-flex items-center gap-2 rounded-full bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-glow">
          <Plus className="size-4" /> Nouvelle prestation
        </button>
      </div>

      <div className="mt-8 rounded-2xl border border-border bg-card/40 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-secondary/50 text-xs uppercase tracking-wider text-muted-foreground">
            <tr>
              <th className="text-left p-4">Nom</th>
              <th className="text-left p-4">Catégorie</th>
              <th className="text-left p-4">Prix</th>
              <th className="text-left p-4">État</th>
              <th className="text-right p-4">Actions</th>
            </tr>
          </thead>
          <tbody>
            {data?.services.map((s) => {
              const cat = data.categories.find((c) => c.id === s.category_id);
              return (
                <tr key={s.id} className="border-t border-border">
                  <td className="p-4">
                    <div className="font-medium flex items-center gap-2">
                      {s.featured && <Star className="size-3.5 text-gold fill-gold" />}
                      {s.name}
                    </div>
                    {s.tagline && <div className="text-xs text-muted-foreground">{s.tagline}</div>}
                  </td>
                  <td className="p-4 text-muted-foreground">{cat?.name ?? "—"}</td>
                  <td className="p-4 font-mono">{formatPrice(s.price_cents, s.price_suffix)}</td>
                  <td className="p-4">
                    {s.published
                      ? <span className="inline-flex items-center gap-1 text-xs text-primary"><Eye className="size-3" /> Publié</span>
                      : <span className="inline-flex items-center gap-1 text-xs text-muted-foreground"><EyeOff className="size-3" /> Brouillon</span>}
                  </td>
                  <td className="p-4">
                    <div className="flex justify-end gap-1">
                      <button onClick={() => setEditing(s)} className="p-2 rounded hover:bg-secondary"><Pencil className="size-4" /></button>
                      <button onClick={() => confirm(`Supprimer "${s.name}" ?`) && del.mutate(s.id!)} className="p-2 rounded hover:bg-destructive/20 text-destructive"><Trash2 className="size-4" /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {editing && (
        <ServiceForm
          service={editing}
          categories={data?.categories ?? []}
          onCancel={() => setEditing(null)}
          onSave={(s) => save.mutate(s)}
          saving={save.isPending}
        />
      )}
    </div>
  );
}

function ServiceForm({ service, categories, onCancel, onSave, saving }: { service: Service; categories: any[]; onCancel: () => void; onSave: (s: Service) => void; saving: boolean }) {
  const [form, setForm] = useState<Service>(service);
  const [featuresText, setFeaturesText] = useState(form.features.join("\n"));
  const [idealText, setIdealText] = useState(form.ideal_for.join("\n"));
  const [priceEuros, setPriceEuros] = useState(String(form.price_cents / 100));

  function submit(e: React.FormEvent) {
    e.preventDefault();
    onSave({
      ...form,
      price_cents: Math.round(parseFloat(priceEuros || "0") * 100),
      features: featuresText.split("\n").map((x) => x.trim()).filter(Boolean),
      ideal_for: idealText.split("\n").map((x) => x.trim()).filter(Boolean),
    });
  }

  return (
    <div className="fixed inset-0 z-50 bg-background/80 backdrop-blur grid place-items-center p-4 overflow-auto">
      <form onSubmit={submit} className="w-full max-w-2xl bg-card border border-border rounded-2xl p-8 my-8 shadow-elegant">
        <div className="flex items-center justify-between mb-6">
          <h2 className="font-display text-2xl font-bold">{form.id ? "Modifier" : "Nouvelle"} prestation</h2>
          <button type="button" onClick={onCancel} className="p-2 rounded hover:bg-secondary"><X className="size-4" /></button>
        </div>
        <div className="space-y-4">
          <Field label="Nom"><input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className={inp} /></Field>
          <Field label="Catégorie">
            <select value={form.category_id ?? ""} onChange={(e) => setForm({ ...form, category_id: e.target.value || null })} className={inp}>
              <option value="">— Aucune —</option>
              {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </Field>
          <Field label="Accroche"><input value={form.tagline ?? ""} onChange={(e) => setForm({ ...form, tagline: e.target.value })} className={inp} /></Field>
          <Field label="Description"><textarea rows={3} value={form.description ?? ""} onChange={(e) => setForm({ ...form, description: e.target.value })} className={inp} /></Field>
          <div className="grid grid-cols-3 gap-4">
            <Field label="Prix (€)"><input type="number" step="0.01" value={priceEuros} onChange={(e) => setPriceEuros(e.target.value)} className={inp} /></Field>
            <Field label="Suffixe prix"><input placeholder="/mois, +…" value={form.price_suffix ?? ""} onChange={(e) => setForm({ ...form, price_suffix: e.target.value })} className={inp} /></Field>
            <Field label="Ordre"><input type="number" value={form.sort_order} onChange={(e) => setForm({ ...form, sort_order: parseInt(e.target.value) || 0 })} className={inp} /></Field>
          </div>
          <Field label="Fonctionnalités (une par ligne)"><textarea rows={5} value={featuresText} onChange={(e) => setFeaturesText(e.target.value)} className={inp} /></Field>
          <Field label="Idéal pour (un par ligne)"><textarea rows={3} value={idealText} onChange={(e) => setIdealText(e.target.value)} className={inp} /></Field>
          <div className="flex gap-6">
            <label className="flex items-center gap-2 text-sm">
              <input type="checkbox" checked={form.featured} onChange={(e) => setForm({ ...form, featured: e.target.checked })} /> Best-seller
            </label>
            <label className="flex items-center gap-2 text-sm">
              <input type="checkbox" checked={form.published} onChange={(e) => setForm({ ...form, published: e.target.checked })} /> Publié
            </label>
          </div>
        </div>
        <div className="mt-8 flex justify-end gap-3">
          <button type="button" onClick={onCancel} className="px-5 py-2 rounded-full text-sm border border-border">Annuler</button>
          <button disabled={saving} type="submit" className="px-5 py-2 rounded-full text-sm bg-primary text-primary-foreground shadow-glow disabled:opacity-50">
            {saving ? "..." : "Enregistrer"}
          </button>
        </div>
      </form>
    </div>
  );
}

const inp = "mt-1.5 w-full rounded-lg bg-input/60 border border-border px-3 py-2 text-sm focus:outline-none focus:border-primary";
function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return <label className="block"><span className="text-xs font-medium text-muted-foreground">{label}</span>{children}</label>;
}
