"use client";

import { API_BASE_URL, getAuthHeaders } from "@/lib/api";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Search, Mail, Phone, User, Loader2, Trash2 } from "lucide-react";

interface Client {
    id: number;
    full_name: string;
    email: string;
    phone_number: string;
    status: string;
    address: string;
    created_at: string;
}

export default function ClientsPage() {
    const [clients, setClients] = useState<Client[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState("");

    // Dialog state
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [formData, setFormData] = useState({
        first_name: "",
        last_name: "",
        email: "",
        phone_number: "",
        address: "",
        id_type: "National ID",
        id_number: "",
        gender: "male",
        occupation: "",
        next_of_kin_name: "",
        next_of_kin_phone: "",
    });

    const fetchClients = () => {
        setLoading(true);
        fetch(`${API_BASE_URL}/clients/`, { headers: getAuthHeaders() })
            .then(res => res.json())
            .then(data => {
                if (data.results) {
                    setClients(data.results);
                } else if (Array.isArray(data)) {
                    setClients(data);
                }
                setLoading(false);
            })
            .catch(err => {
                console.error("Failed to fetch clients:", err);
                setLoading(false);
            });
    };

    useEffect(() => {
        fetchClients();
    }, []);

    const handleAddClient = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            const res = await fetch(`${API_BASE_URL}/clients/`, {
                method: "POST",
                headers: getAuthHeaders(),
                body: JSON.stringify(formData)
            });
            if (res.ok) {
                setIsDialogOpen(false);
                setFormData({
                    first_name: "", last_name: "", email: "", phone_number: "", address: "", id_type: "National ID", id_number: "",
                    gender: "male", occupation: "", next_of_kin_name: "", next_of_kin_phone: ""
                });
                fetchClients(); // refresh list
            } else {
                console.error("Failed to create:", await res.text());
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsSubmitting(false);
        }
    };

    const filteredClients = clients.filter(client =>
        client.full_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        client.email?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        client.phone_number?.includes(searchQuery)
    );

    const [deleteTarget, setDeleteTarget] = useState<Client | null>(null);
    const [isDeleting, setIsDeleting] = useState(false);

    const deleteClient = async () => {
        if (!deleteTarget) return;
        setIsDeleting(true);
        try {
            const res = await fetch(`${API_BASE_URL}/clients/${deleteTarget.id}/`, {
                method: "DELETE",
                headers: getAuthHeaders(),
            });
            if (res.ok || res.status === 204) {
                setClients(prev => prev.filter(c => c.id !== deleteTarget.id));
                setDeleteTarget(null);
            } else {
                alert("Delete failed: " + (await res.text()));
            }
        } catch (e) {
            alert("Network error");
        } finally {
            setIsDeleting(false);
        }
    };

    return (
        <>
            <div className="flex-1 space-y-6 pb-12">
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-3xl font-black tracking-tight text-foreground">Clients</h2>
                        <p className="text-muted-foreground mt-1 text-sm font-medium">
                            Manage clients, leads, and overarching lifetime valuations.
                        </p>
                    </div>

                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button className="bg-primary hover:bg-primary/90 text-primary-foreground font-black uppercase text-[10px] tracking-widest rounded-xl px-6 h-10 shadow-lg shadow-primary/20 transition-all active:scale-95">
                                + Add Client
                            </Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-[425px]">
                            <DialogHeader>
                                <DialogTitle>Add New Client</DialogTitle>
                            </DialogHeader>
                            <form onSubmit={handleAddClient} className="space-y-4 py-4">
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="first_name">First Name</Label>
                                        <Input id="first_name" required value={formData.first_name} onChange={e => setFormData({ ...formData, first_name: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="last_name">Last Name</Label>
                                        <Input id="last_name" required value={formData.last_name} onChange={e => setFormData({ ...formData, last_name: e.target.value })} />
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="email">Email</Label>
                                    <Input id="email" type="email" required value={formData.email} onChange={e => setFormData({ ...formData, email: e.target.value })} />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="phone">Phone Number</Label>
                                    <Input id="phone" required value={formData.phone_number} onChange={e => setFormData({ ...formData, phone_number: e.target.value })} />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="id_number">National ID / Passport</Label>
                                        <Input id="id_number" required value={formData.id_number} onChange={e => setFormData({ ...formData, id_number: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="gender">Gender</Label>
                                        <select
                                            id="gender"
                                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                            value={formData.gender}
                                            onChange={e => setFormData({ ...formData, gender: e.target.value })}
                                        >
                                            <option value="male">Male</option>
                                            <option value="female">Female</option>
                                            <option value="other">Other</option>
                                        </select>
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="address">Address</Label>
                                    <Input id="address" value={formData.address} onChange={e => setFormData({ ...formData, address: e.target.value })} />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label htmlFor="occupation">Occupation</Label>
                                        <Input id="occupation" value={formData.occupation} onChange={e => setFormData({ ...formData, occupation: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="nok_name">Next of Kin Name</Label>
                                        <Input id="nok_name" value={formData.next_of_kin_name} onChange={e => setFormData({ ...formData, next_of_kin_name: e.target.value })} />
                                    </div>
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="nok_phone">Next of Kin Phone</Label>
                                    <Input id="nok_phone" value={formData.next_of_kin_phone} onChange={e => setFormData({ ...formData, next_of_kin_phone: e.target.value })} />
                                </div>
                                <DialogFooter className="pt-4">
                                    <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                                    <Button type="submit" disabled={isSubmitting}>
                                        {isSubmitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null} Save Client
                                    </Button>
                                </DialogFooter>
                            </form>
                        </DialogContent>
                    </Dialog>
                </div>

                <Card className="rounded-3xl shadow-card border-none bg-card overflow-hidden">
                    {/* Table Toolbar */}
                    <div className="p-6 border-b bg-muted/10 flex flex-col sm:flex-row gap-6 justify-between items-center">
                        <div className="relative w-full sm:max-w-md">
                            <Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                            <Input
                                placeholder="Search by name, email, or phone..."
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="pl-11 w-full bg-background border-border/10 rounded-xl h-11 focus:ring-primary/20"
                            />
                        </div>
                        <div className="flex items-center gap-3 w-full sm:w-auto">
                            <Button variant="outline" className="w-full sm:w-auto rounded-xl font-bold border-border/10 hover:bg-accent">Export CSV</Button>
                            <Button variant="outline" className="w-full sm:w-auto rounded-xl font-bold border-border/10 hover:bg-accent">Filters</Button>
                        </div>
                    </div>

                    {/* Data Table */}
                    <div className="relative w-full overflow-auto">
                        <Table>
                            <TableHeader className="bg-muted/10">
                                <TableRow className="hover:bg-transparent border-b border-border/5">
                                    <TableHead className="w-[300px] font-black uppercase text-[10px] tracking-widest px-6 py-4">Client / Lead</TableHead>
                                    <TableHead className="font-black uppercase text-[10px] tracking-widest px-6 py-4">Contact Information</TableHead>
                                    <TableHead className="font-black uppercase text-[10px] tracking-widest px-6 py-4">Status</TableHead>
                                    <TableHead className="font-black uppercase text-[10px] tracking-widest px-6 py-4">Registered</TableHead>
                                    <TableHead className="text-right font-black uppercase text-[10px] tracking-widest px-6 py-4">Actions</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={5} className="h-32 text-center text-slate-500">
                                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 mx-auto" style={{ borderColor: "var(--dynamic-primary, #2563eb)" }}></div>
                                        </TableCell>
                                    </TableRow>
                                ) : filteredClients.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={5} className="h-32 text-center text-slate-500">
                                            No clients found matching the search criteria.
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    filteredClients.map((client) => (
                                        <TableRow key={client.id} className="group hover:bg-muted/5 transition-colors border-b border-border/5 cursor-pointer">
                                            <TableCell className="px-6 py-4">
                                                <Link href={`/clients/${client.id}`} className="flex items-center gap-4">
                                                    <div className="w-12 h-12 rounded-2xl bg-primary/10 flex items-center justify-center font-black text-primary border border-primary/10 shadow-sm group-hover:scale-110 transition-transform">
                                                        {client.full_name.charAt(0)}
                                                    </div>
                                                    <div>
                                                        <p className="font-black text-foreground group-hover:text-primary transition-colors">{client.full_name}</p>
                                                        <p className="text-[11px] font-medium text-muted-foreground">{client.address || "No address on file"}</p>
                                                    </div>
                                                </Link>
                                            </TableCell>
                                            <TableCell className="px-6 py-4">
                                                <div className="space-y-2">
                                                    <div className="flex items-center text-[13px] text-muted-foreground font-medium">
                                                        <Mail className="h-3.5 w-3.5 mr-2 text-primary/60" /> {client.email || 'N/A'}
                                                    </div>
                                                    <div className="flex items-center text-[13px] text-muted-foreground font-medium">
                                                        <Phone className="h-3.5 w-3.5 mr-2 text-primary/60" /> {client.phone_number}
                                                    </div>
                                                </div>
                                            </TableCell>
                                            <TableCell className="px-6 py-4">
                                                <Badge
                                                    variant="secondary"
                                                    className={client.status === "active"
                                                        ? "bg-emerald-500/10 text-emerald-600 border-none font-black text-[10px] tracking-widest uppercase px-3"
                                                        : "bg-muted text-muted-foreground border-none font-black text-[10px] tracking-widest uppercase px-3"}
                                                >
                                                    {client.status}
                                                </Badge>
                                            </TableCell>
                                            <TableCell className="text-[13px] font-medium text-muted-foreground px-6 py-4">
                                                {new Date(client.created_at).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}
                                            </TableCell>
                                            <TableCell className="text-right px-6 py-4">
                                                <div className="flex items-center justify-end gap-2">
                                                    <Link href={`/clients/${client.id}`}>
                                                        <Button variant="outline" size="sm" className="rounded-xl font-black uppercase text-[10px] tracking-widest border-primary/20 text-primary hover:bg-primary hover:text-white transition-all">
                                                            <User className="h-3.5 w-3.5 mr-1.5" /> View Profile
                                                        </Button>
                                                    </Link>
                                                    <Button variant="ghost" size="sm" className="h-8 w-8 p-0 rounded-lg text-muted-foreground hover:text-rose-500 hover:bg-rose-500/10 transition-all" onClick={() => setDeleteTarget(client)}>
                                                        <Trash2 className="h-3.5 w-3.5" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </div>
                </Card>
            </div>

            <Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
                <DialogContent className="sm:max-w-[400px] rounded-2xl">
                    <DialogHeader>
                        <DialogTitle className="text-rose-600 flex items-center gap-2">
                            <Trash2 className="h-5 w-5" /> Delete Client
                        </DialogTitle>
                        <DialogDescription>
                            Permanently delete <strong>{deleteTarget?.full_name}</strong>? This will not delete their contracts but will unlink them.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter className="gap-2 pt-2">
                        <Button variant="outline" className="rounded-xl" onClick={() => setDeleteTarget(null)}>Cancel</Button>
                        <Button variant="destructive" className="rounded-xl" onClick={deleteClient} disabled={isDeleting}>
                            {isDeleting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
                            Yes, Delete Client
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}
