"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Plus, Edit, Trash2, Loader2, Briefcase, Image as ImageIcon } from "lucide-react";
import Image from "next/image";
import { stripHtml, getDirectDriveLink } from "@/lib/text";

type Service = { id: string; title: string; description: string; images: string[]; createdAt: string };

export default function AdminServicesPage() {
    const [services, setServices] = useState<Service[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleting, setDeleting] = useState<string | null>(null);

    const fetchServices = useCallback(async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/services");
            const data = await res.json();
            setServices(Array.isArray(data) ? data : []);
        } catch { setServices([]); }
        finally { setLoading(false); }
    }, []);

    useEffect(() => { fetchServices(); }, [fetchServices]);

    const handleDelete = async (id: string, title: string) => {
        if (!confirm(`Supprimer le service "${title}" ?`)) return;
        setDeleting(id);
        try {
            const res = await fetch(`/api/services/${id}`, { method: "DELETE" });
            if (res.ok) {
                setServices(prev => prev.filter(s => s.id !== id));
            } else {
                alert("Erreur lors de la suppression");
            }
        } catch { alert("Erreur lors de la suppression"); }
        finally { setDeleting(null); }
    };

    return (
        <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "2.5rem" }}>
                <div>
                    <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Services</h1>
                    <p style={{ color: "#64748b" }}>Gérez les services que vous proposez.</p>
                </div>
                <Link href="/admin/services/new" style={{ display: "flex", alignItems: "center", gap: "0.5rem", padding: "0.75rem 1.5rem", background: "#2563eb", color: "#fff", borderRadius: "0.875rem", fontWeight: 800, textDecoration: "none" }}>
                    <Plus size={18} /> Nouveau Service
                </Link>
            </div>

            <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", overflow: "hidden" }}>
                {loading ? (
                    <div style={{ display: "flex", justifyContent: "center", padding: "4rem" }}><Loader2 size={32} className="animate-spin" style={{ color: "#2563eb" }} /></div>
                ) : services.length === 0 ? (
                    <div style={{ textAlign: "center", padding: "5rem", color: "#94a3b8" }}>
                        <Briefcase size={40} style={{ margin: "0 auto 1rem", opacity: 0.5 }} />
                        <p style={{ fontWeight: 700, fontSize: "1.1rem" }}>Aucun service enregistré</p>
                    </div>
                ) : (
                    <div style={{ overflowX: "auto" }}>
                        <table style={{ width: "100%", borderCollapse: "collapse" }}>
                            <thead>
                                <tr style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0" }}>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "left", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Service</th>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "left", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Description</th>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "right", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {services.map(s => (
                                    <tr key={s.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
                                                <div style={{ width: 48, height: 48, borderRadius: 10, background: "#f1f5f9", overflow: "hidden", position: "relative", border: "1px solid #e2e8f0", flexShrink: 0 }}>
                                                    {s.images?.[0] ? (
                                                        <Image src={getDirectDriveLink(s.images[0])} alt="" fill style={{ objectFit: "cover" }} />
                                                    ) : (
                                                        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", color: "#cbd5e1" }}>
                                                            <ImageIcon size={20} />
                                                        </div>
                                                    )}
                                                </div>
                                                <p style={{ fontWeight: 800, color: "#0f172a" }}>{s.title}</p>
                                            </div>
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem", color: "#64748b", fontSize: "0.85rem", maxWidth: "20rem" }}>
                                            <p style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                                                {stripHtml(s.description)}
                                            </p>
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem", textAlign: "right" }}>
                                            <div style={{ display: "flex", gap: "0.5rem", justifyContent: "flex-end" }}>
                                                <Link href={`/admin/services/${s.id}/edit`} style={{ width: 34, height: 34, borderRadius: 8, background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", color: "#475569" }}><Edit size={15} /></Link>
                                                <button onClick={() => handleDelete(s.id, s.title)} disabled={deleting === s.id} style={{ width: 34, height: 34, borderRadius: 8, background: "rgba(239,68,68,0.06)", display: "flex", alignItems: "center", justifyContent: "center", color: "#ef4444", cursor: "pointer", border: "none" }}>
                                                    {deleting === s.id ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={15} />}
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
}
