// @ts-nocheck
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Users, Mail, Phone, Edit, MapPin, Award, RefreshCw, Clock} from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { createPanelPageUrl } from "@/utils";
import { useCustomer } from "@/hooks/useCustomer";
import { toast } from "sonner";

import CustomerForm from "../components/subscriptions/CustomerForm";

export default function CustomersPage() {
    const {
        selectedCompany,
        customers,
        total,
        page,
        perPage,
        totalPages,
        searchTerm,
        showForm,
        editingCustomer,
        isLoading,
        isFetching,
        isUpdatingCategories,
        setSearchTerm,
        setPage,
        setPerPage,
        openCreateForm,
        openEditForm,
        closeForm,
        submitForm,
        updateCategories,
    } = useCustomer();

    const handleUpdateCategories = async () => {
        if (!selectedCompany) {
            return;
        }

        try {
            const success = await updateCategories();
            if (success) {
                toast.success("Categorías actualizadas correctamente");
            }
        } catch (error) {
            toast.error("Error al actualizar categorías: " + (error?.message || "Error inesperado"));
        }
    };

    const statusColors = {
        active: "bg-emerald-100 text-emerald-800",
        inactive: "bg-gray-100 text-gray-800",
        suspended: "bg-red-100 text-red-800"
    };

    const statusLabels = {
        active: "Activo",
        inactive: "Inactivo",
        suspended: "Suspendido"
    };

    if (isLoading) {
        return (
            <div className="p-8">
                <div className="animate-pulse space-y-6">
                    <div className="h-8 bg-gray-200 rounded w-1/4"></div>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        {[...Array(6)].map((_, i) => (
                            <div key={i} className="h-48 bg-gray-200 rounded-xl"></div>
                        ))}
                    </div>
                </div>
            </div>
        );
    }

    const getCustomerAntiquity = (createdAt: string) => {
        if (!createdAt) return "Sin fecha";

        const created = new Date(createdAt);
        if (Number.isNaN(created.getTime())) return "Fecha inválida";

        const now = new Date();

        const diffMs = now.getTime() - created.getTime();
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffDays < 0) return "0 días";
        if (diffDays === 0) return "Hoy";

        if (diffDays < 7) {
            return `${diffDays} día${diffDays !== 1 ? 's' : ''}`;
        }

        const weeks = Math.floor(diffDays / 7);
        if (weeks < 4) {
            return `${weeks} semana${weeks !== 1 ? 's' : ''}`;
        }

        const months = Math.floor(diffDays / 30);
        if (months < 12) {
            return `${months} mes${months !== 1 ? 'es' : ''}`;
        }

        const years = Math.floor(months / 12);
        return `${years} año${years !== 1 ? 's' : ''}`;
    };

    return (
        <div className="p-4 lg:p-8 space-y-8">
            <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4">
                <div>
                    <h1 className="text-3xl font-bold text-gradient">Clientes</h1>
                    <p className="text-gray-600 mt-1">
                        {selectedCompany?.name} • {total} clientes
                    </p>
                </div>
                <div className="flex gap-2">
                    <Button
                        onClick={handleUpdateCategories}
                        variant="outline"
                        disabled={!selectedCompany || isUpdatingCategories}
                        className="border-amber-300 hover:bg-amber-50"
                    >
                        <RefreshCw className={`w-4 h-4 mr-2 ${isUpdatingCategories ? 'animate-spin' : ''}`} />
                        Actualizar Categorías
                    </Button>
                    <Button
                        onClick={openCreateForm}
                        className="bg-gradient-to-r from-emerald-500 to-emerald-600"
                        disabled={!selectedCompany}
                    >
                        <Plus className="w-4 h-4 mr-2" />
                        Nuevo Cliente
                    </Button>
                </div>
            </div>

            <Card className="glass-card">
                <CardContent className="p-4">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div className="md:col-span-2">
                            <Label className="mb-2 block">Buscar</Label>
                            <Input
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                placeholder="Nombre, correo, RUT o teléfono (mínimo 3 caracteres)"
                            />
                            <p className="text-xs text-gray-500 mt-1">
                                Se busca automáticamente al dejar de escribir.
                            </p>
                        </div>
                        <div>
                            <Label className="mb-2 block">Registros por página</Label>
                            <Select value={String(perPage)} onValueChange={(value) => setPerPage(Number(value))}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="12">12</SelectItem>
                                    <SelectItem value="24">24</SelectItem>
                                    <SelectItem value="48">48</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                </CardContent>
            </Card>

            {showForm && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
                    <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                        <CustomerForm
                            customer={editingCustomer}
                            companyId={selectedCompany?.id}
                            onSave={submitForm}
                            onCancel={closeForm}
                        />
                    </div>
                </div>
            )}

            {isFetching && (
                <div className="flex justify-end">
                    <Badge className="bg-amber-100 text-amber-800">Actualizando...</Badge>
                </div>
            )}

            {customers.length === 0 ? (
                <div className="text-center py-16">
                    <Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                    <h2 className="text-xl font-semibold text-gray-900 mb-2">No hay clientes</h2>
                    <p className="text-gray-500 mb-6">Agrega tu primer cliente para gestionar suscripciones</p>
                    <Button
                        onClick={openCreateForm}
                        className="bg-gradient-to-r from-emerald-500 to-emerald-600"
                    >
                        <Plus className="w-4 h-4 mr-2" />
                        Crear Primer Cliente
                    </Button>
                </div>
            ) : (
                <>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {customers.map((customer) => (
                            <Card key={customer.id} className="glass-card border-white/20 hover:shadow-xl transition-all duration-300">
                                <CardHeader>
                                    <div className="flex items-start justify-between">
                                        <div className="flex-1">
                                            <CardTitle className="text-lg">{customer.name}</CardTitle>
                                            {customer.referral_category && (
                                                <div className="flex items-center gap-1 mt-2">
                                                    <Award className="w-3.5 h-3.5 text-amber-600" />
                                                    <span className="text-xs font-semibold text-amber-800">{customer.referral_category}</span>
                                                </div>
                                            )}
                                        </div>
                                        <Badge className={statusColors[customer.status]}>
                                            {statusLabels[customer.status]}
                                        </Badge>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-3">
                                    {customer.created_at && (
                                        <>
                                            <div className="flex items-center gap-2 text-sm text-gray-500">
                                                <Clock className="w-4 h-4" />
                                                Antigüedad: {getCustomerAntiquity(customer.created_at)}
                                            </div>
                                            <div className="text-xs text-gray-500">
                                                Creado: {new Date(customer.created_at).toLocaleString("es-CL")}
                                            </div>
                                        </>
                                    )}
                                    <div className="flex items-center gap-2 text-sm text-gray-600">
                                        <Mail className="w-4 h-4" />
                                        {customer.email}
                                    </div>
                                    {customer.phone && (
                                        <div className="flex items-center gap-2 text-sm text-gray-600">
                                            <Phone className="w-4 h-4" />
                                            {customer.phone}
                                        </div>
                                    )}
                                    {customer.tax_id && (
                                        <div className="text-sm text-gray-600">
                                            <strong>Tax ID:</strong> {customer.tax_id}
                                        </div>
                                    )}
                                    <div className="flex gap-2 mt-4">
                                        <Button
                                            variant="outline"
                                            className="flex-1"
                                            onClick={() => openEditForm(customer)}
                                        >
                                            <Edit className="w-4 h-4 mr-2" />
                                            Editar
                                        </Button>
                                        <Link href={createPanelPageUrl("customer-addresses") + `?customer_id=${customer.id}`}>
                                            <Button variant="outline" className="w-full">
                                                <MapPin className="w-4 h-4 mr-2" />
                                                Direcciones
                                            </Button>
                                        </Link>
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>

                    <Card className="glass-card">
                        <CardContent className="p-4 flex items-center justify-between gap-3">
                            <p className="text-sm text-gray-600">
                                Página {page} de {totalPages} ({customers.length} registros cargados en esta página)
                            </p>
                            <div className="flex items-center gap-2">
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setPage(Math.max(1, page - 1))}
                                    disabled={page <= 1}
                                >
                                    Anterior
                                </Button>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => setPage(Math.min(totalPages, page + 1))}
                                    disabled={page >= totalPages}
                                >
                                    Siguiente
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </>
            )}
        </div>
    );
}
