"use client";

import { useState } from "react";
import { PawPrint, RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { apiFetch, type Pet } from "./types";

interface Props { pets: Pet[]; onCreated: () => void; }

const petTypes = [
    { value: "dog", label: "🐕 Perro" },
    { value: "cat", label: "🐱 Gato" },
    { value: "bird", label: "🐦 Pájaro" },
    { value: "rabbit", label: "🐰 Conejo" },
    { value: "hamster", label: "🐹 Hámster" }
];

export default function PetsTab({ pets, onCreated }: Props) {
    const [petName, setPetName] = useState("");
    const [petType, setPetType] = useState("dog");
    const [petBreed, setPetBreed] = useState("");
    const [petPersonality, setPetPersonality] = useState("");
    const [petLoading, setPetLoading] = useState(false);

    const handleCreatePet = async () => {
        if (!petName.trim()) { toast.error("Dale un nombre a tu mascota"); return; }
        setPetLoading(true);
        try {
            const result = await apiFetch("/pets", {
                method: "POST",
                body: JSON.stringify({
                    name: petName, type: petType,
                    breed: petBreed || undefined,
                    personality: petPersonality || undefined,
                    generateReference: true
                }),
            });
            if (result.success) {
                toast.success(`Mascota "${petName}" creada (+${result.engagementBoost}% engagement)`);
                setPetName(""); setPetBreed(""); setPetPersonality("");
                onCreated();
            } else toast.error(result.error);
        } catch { toast.error("Error"); }
        finally { setPetLoading(false); }
    };

    return (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="bg-slate-900/50 border-slate-800">
                <CardHeader>
                    <CardTitle className="flex items-center gap-2"><PawPrint className="h-5 w-5 text-amber-400" />Crear Mascota</CardTitle>
                    <CardDescription>Las mascotas aumentan el engagement hasta un 35%</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <Label className="text-xs text-slate-400">Nombre</Label>
                            <Input placeholder="Max, Luna..." value={petName} onChange={(e) => setPetName(e.target.value)} className="bg-slate-800 border-slate-700 mt-1" />
                        </div>
                        <div>
                            <Label className="text-xs text-slate-400">Tipo</Label>
                            <Select value={petType} onValueChange={setPetType}>
                                <SelectTrigger className="bg-slate-800 border-slate-700 mt-1"><SelectValue /></SelectTrigger>
                                <SelectContent>
                                    {petTypes.map((pt) => (
                                        <SelectItem key={pt.value} value={pt.value}>{pt.label}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <Label className="text-xs text-slate-400">Raza (opcional)</Label>
                            <Input placeholder="Golden Retriever..." value={petBreed} onChange={(e) => setPetBreed(e.target.value)} className="bg-slate-800 border-slate-700 mt-1" />
                        </div>
                        <div>
                            <Label className="text-xs text-slate-400">Personalidad</Label>
                            <Select value={petPersonality} onValueChange={setPetPersonality}>
                                <SelectTrigger className="bg-slate-800 border-slate-700 mt-1"><SelectValue placeholder="Seleccionar" /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="playful">Juguetón</SelectItem>
                                    <SelectItem value="calm">Tranquilo</SelectItem>
                                    <SelectItem value="energetic">Energético</SelectItem>
                                    <SelectItem value="curious">Curioso</SelectItem>
                                    <SelectItem value="lazy">Perezoso</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <Button onClick={handleCreatePet} disabled={petLoading} className="w-full bg-amber-600 hover:bg-amber-700">
                        {petLoading ? <RefreshCw className="h-4 w-4 mr-2 animate-spin" /> : <PawPrint className="h-4 w-4 mr-2" />}Crear Mascota
                    </Button>
                </CardContent>
            </Card>

            <Card className="bg-slate-900/50 border-slate-800">
                <CardHeader><CardTitle>Mis Mascotas</CardTitle></CardHeader>
                <CardContent>
                    <ScrollArea className="h-64">
                        {pets.length === 0 ? (
                            <div className="text-center py-8 text-slate-400">
                                <PawPrint className="h-12 w-12 mx-auto mb-3 opacity-50" />
                                <p>No tienes mascotas</p>
                                <p className="text-xs mt-1">Las mascotas aumentan el engagement</p>
                            </div>
                        ) : (
                            <div className="space-y-2">
                                {pets.map((p) => (
                                    <div key={p.id} className="p-3 rounded-lg bg-slate-800/50 flex items-center justify-between">
                                        <div className="flex items-center gap-3">
                                            <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-amber-500 to-orange-500 flex items-center justify-center">
                                                <PawPrint className="h-5 w-5 text-white" />
                                            </div>
                                            <div>
                                                <p className="font-medium">{p.name}</p>
                                                <p className="text-xs text-slate-400">{p.breed || p.type} • {p.personality || "Sin personalidad"}</p>
                                            </div>
                                        </div>
                                        <Badge className="bg-green-500/20 text-green-400">+35%</Badge>
                                    </div>
                                ))}
                            </div>
                        )}
                    </ScrollArea>
                </CardContent>
            </Card>
        </div>
    );
}
