// @ts-nocheck
import React from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Trash2, Edit2, Search, Tag, Users } from "lucide-react";
import { toast } from "sonner";
import { createPanelPageUrl } from "@/utils";
import { useCategory } from "@/hooks/useCategory";

export default function CategoriesPage() {
    const {
      selectedCompany,
      categories,
      filteredCategories,
      genders,
      showForm,
      editingCategory,
      searchTerm,
      formData,
      isLoading,
      setSearchTerm,
      setFormData,
      getProductsCountByCategory,
      openCreateForm,
      openEditForm,
      closeForm,
      submitForm,
      removeCategory,
    } = useCategory();

    const handleSubmit = async (e) => {
      e.preventDefault();
      try {
        await submitForm();
        toast.success(
          editingCategory ? "Categoría actualizada exitosamente" : "Categoría creada exitosamente"
        );
      } catch (error) {
        toast.error(
          `${editingCategory ? "Error al actualizar categoría" : "Error al crear categoría"}: ${
            error.message
          }`
        );
      }
    };

    const handleDelete = async (category) => {
      if (!window.confirm(`¿Estás seguro de eliminar la categoría "${category.name}"?`)) {
        return;
      }
      try {
        await removeCategory(category);
        toast.success("Categoría eliminada exitosamente");
      } catch (error) {
        toast.error(error.message);
      }
    };

    const genderLabels = {
        female: "Mujer",
        male: "Hombre",
        unisex: "Unisex",
        // Compatibilidad de datos legacy
        mujer: "Mujer",
        hombre: "Hombre",
        teen: "Unisex",
    };

    const genderColors = {
        female: "bg-pink-100 text-pink-800",
        male: "bg-blue-100 text-blue-800",
        teen: "bg-purple-100 text-purple-800",
        unisex: "bg-gray-100 text-gray-800",
        // Compatibilidad de datos legacy
        mujer: "bg-pink-100 text-pink-800",
        hombre: "bg-blue-100 text-blue-800",
    };

    if (!selectedCompany) {
        return (
            <div className="flex items-center justify-center h-screen">
                <p className="text-gray-500">Cargando...</p>
            </div>
        );
    }

    return (
        <div className="p-6 max-w-7xl mx-auto space-y-6">
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-3xl font-bold text-gray-900">Categorías de Productos</h1>
                    <p className="text-gray-500 mt-1">Gestiona las categorías de tu catálogo</p>
                </div>
                <div className="flex gap-2">
                    <Link href={createPanelPageUrl("genders")}>
                        <Button variant="outline">
                            <Users className="w-4 h-4 mr-2" />
                            Gestionar Géneros
                        </Button>
                    </Link>
                    <Button onClick={openCreateForm} className="bg-blue-600 hover:bg-blue-700">
                        <Plus className="w-4 h-4 mr-2" />
                        Nueva Categoría
                    </Button>
                </div>
            </div>

            <Card>
                <CardContent className="pt-6">
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                        <Input
                            placeholder="Buscar categorías..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="pl-10"
                        />
                    </div>
                </CardContent>
            </Card>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <Card>
                    <CardContent className="pt-6">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-blue-100 rounded-lg">
                                <Tag className="w-6 h-6 text-blue-600" />
                            </div>
                            <div>
                                <p className="text-sm text-gray-500">Total</p>
                                <p className="text-2xl font-bold">{categories.length}</p>
                            </div>
                        </div>
                    </CardContent>
                </Card>
                {["female", "male", "unisex"].map((gender) => (
                    <Card key={gender}>
                        <CardContent className="pt-6">
                            <div className="flex items-center gap-3">
                                <div className={`p-2 rounded-lg ${genderColors[gender].replace("text-", "bg-").replace("800", "100")}`}>
                                    <Tag className={`w-6 h-6 ${genderColors[gender].replace("bg-", "text-")}`} />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500">{genderLabels[gender]}</p>
                                    <p className="text-2xl font-bold">
                                        {categories.filter((c) => (c.gender || "unisex") === gender).length}
                                    </p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {isLoading ? (
                <div className="text-center py-12">
                    <p className="text-gray-500">Cargando categorías...</p>
                </div>
            ) : filteredCategories.length === 0 ? (
                <Card>
                    <CardContent className="py-12 text-center">
                        <Tag className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                        <p className="text-gray-500">No hay categorías disponibles</p>
                    </CardContent>
                </Card>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredCategories.map((category) => {
                        const productCount = getProductsCountByCategory(category.id);
                        return (
                            <Card key={category.id} className="hover:shadow-lg transition-shadow">
                                <CardHeader className="pb-3">
                                    <div className="flex justify-between items-start">
                                        <div className="flex-1">
                                            <CardTitle className="text-lg">{category.name}</CardTitle>
                                            <div className="flex gap-2 mt-2">
                                                <Badge className={genderColors[category.gender || "unisex"] || genderColors.unisex}>
                                                    {genderLabels[category.gender || "unisex"] || genderLabels.unisex}
                                                </Badge>
                                                <Badge variant="outline">
                                                    {productCount} producto{productCount !== 1 ? "s" : ""}
                                                </Badge>
                                            </div>
                                        </div>
                                        <div className="flex gap-1">
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                onClick={() => openEditForm(category)}
                                            >
                                                <Edit2 className="w-4 h-4 text-blue-600" />
                                            </Button>
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                onClick={() => handleDelete(category)}
                                                disabled={productCount > 0}
                                            >
                                                <Trash2 className={`w-4 h-4 ${productCount > 0 ? "text-gray-300" : "text-red-600"}`} />
                                            </Button>
                                        </div>
                                    </div>
                                </CardHeader>
                                {category.description && (
                                    <CardContent>
                                        <p className="text-sm text-gray-600">{category.description}</p>
                                    </CardContent>
                                )}
                            </Card>
                        );
                    })}
                </div>
            )}

            <Dialog
                open={showForm}
                onOpenChange={(open) => {
                    if (!open) {
                        closeForm();
                    }
                }}
            >
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>
                            {editingCategory ? "Editar Categoría" : "Nueva Categoría"}
                        </DialogTitle>
                    </DialogHeader>
                    <form onSubmit={handleSubmit}>
                        <div className="space-y-4">
                            <div>
                                <Label>Nombre *</Label>
                                <Input
                                    value={formData.name}
                                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    required
                                    placeholder="Ej: Colonias Premium"
                                />
                            </div>
                            <div>
                                <Label>Género</Label>
                                <Select
                                    value={formData.gender}
                                    onValueChange={(value) => setFormData({ ...formData, gender: value })}
                                >
                                    <SelectTrigger>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {genders.map((g) => (
                                            <SelectItem key={g.code} value={g.code}>{g.name}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div>
                                <Label>Descripción</Label>
                                <Input
                                    value={formData.description}
                                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                    placeholder="Descripción opcional"
                                />
                            </div>
                        </div>
                        <DialogFooter className="mt-6">
                            <Button type="button" variant="outline" onClick={closeForm}>
                                Cancelar
                            </Button>
                            <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
                                {editingCategory ? "Actualizar" : "Crear"}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </div>
    );
}
