import React, { useState, useEffect, useMemo } from 'react';
import { 
  Server, 
  Plus,
  Edit,
  Trash2,
  Search,
  X,
  Save,
  Package,
  Wrench,
  HelpCircle
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardHeader, CardContent } from '@/components/ui/card';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Loader2 } from 'lucide-react';
import { useContasReceber } from '../../hooks/useContasReceber';
import { useToast } from '../../hooks/useToast';
import { IconPicker, LUCIDE_MAP, PREFIX } from '../../components/IconPicker';
import { cn } from '@/lib/utils';
import { formatCurrency, parseCurrency, formatCurrencyForInput } from '../../utils/dateUtils';

// --- Funções Monetárias (Padrão Prafrot) ---

const CurrencyInput = ({ label, value, onChange, className = '', ...props }) => {
    const [focused, setFocused] = useState(false);
    const [local, setLocal] = useState('');
    const isEmpty = value === '' || value == null;
    const display = focused ? local : (isEmpty ? '' : formatCurrency(value));
    
    return (
        <div className="space-y-1.5 w-full">
            {label && <Label className="text-slate-700 dark:text-slate-300 text-xs font-bold uppercase tracking-wider ml-1">{label}</Label>}
            <Input
                type="text"
                inputMode="decimal"
                className={cn(
                    "bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white focus:border-purple-500",
                    className
                )}
                placeholder="R$ 0,00"
                value={display}
                onFocus={() => { 
                    setFocused(true); 
                    setLocal(isEmpty ? '' : formatCurrencyForInput(value)); 
                }}
                onBlur={() => {
                    const n = parseCurrency(local);
                    onChange(n === '' ? '' : n);
                    setFocused(false);
                }}
                onChange={(e) => setLocal(e.target.value)}
                {...props}
            />
        </div>
    );
};


/** Renderiza ícone Lucide, HTML (bi) ou placeholder para filename. */
function ServicoIcon({ imagem, className }) {
    const box = 'inline-flex items-center justify-center w-8 h-8 rounded-lg bg-purple-100 dark:bg-purple-500/10 border border-purple-200 dark:border-purple-500/20 text-purple-600 dark:text-purple-400 shrink-0';
    
    // Esfera roxa para erro/outros formatos
    const ErrorSphere = () => (
        <span className={cn(box, className)}>
            <div className="w-3 h-3 rounded-full bg-purple-500 shadow-[0_0_8px_rgba(168,85,247,0.5)]" />
        </span>
    );

    if (!imagem || typeof imagem !== 'string') {
        return (
            <span className={cn(box, className)}>
                <Server className="w-4 h-4 text-purple-600 dark:text-purple-400" />
            </span>
        );
    }

    if (imagem.startsWith(PREFIX)) {
        const name = imagem.slice(PREFIX.length);
        const entry = LUCIDE_MAP[name];
        if (entry?.Icon) {
            const Icon = entry.Icon;
            return (
                <span className={cn(box, className)}>
                    <Icon className="w-4 h-4 text-purple-600 dark:text-purple-400" />
                </span>
            );
        }
    }

    // Se for uma string HTML (ex: <i class='bi bi-person'></i>)
    if (imagem.includes('<i') || imagem.includes('<svg')) {
        return (
            <span 
                className={cn(box, className)}
                dangerouslySetInnerHTML={{ __html: imagem }}
            />
        );
    }

    // Qualquer outro formato (filenames, etc) é tratado como erro/esfera
    return <ErrorSphere />;
}

export const ServicesView = ({ services: initialServices = [] }) => {
    const { state, actions } = useContasReceber();
    const toast = useToast();
    const [isLoading, setIsLoading] = useState(false);
    const [services, setServices] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [activeTab, setActiveTab] = useState('Serviço'); // 'Serviço', 'Produto', or 'Sem Tipo'
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingService, setEditingService] = useState(null);
    const [formData, setFormData] = useState({ servico: '', valor: '', imagem: '', tipo_servico: 'Serviço' });
    const [saving, setSaving] = useState(false);
    const [deletingId, setDeletingId] = useState(null);

    // Carrega serviços do backend quando a tab muda
    useEffect(() => {
        const loadServices = async () => {
            setIsLoading(true);
            try {
                // Mapeia tab para parâmetro do backend
                let tipo = undefined;
                if (activeTab === 'Serviço') tipo = 'servico';
                else if (activeTab === 'Produto') tipo = 'produto';
                // 'Sem Tipo' = undefined (busca todos)
                
                const data = await actions?.loadServicos?.(tipo);
                setServices(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error('[ServicesView] Erro ao carregar serviços:', err);
                setServices([]);
            } finally {
                setIsLoading(false);
            }
        };
        loadServices();
    }, [activeTab, actions.loadServicos]);

    // Filtro de busca (apenas no frontend para pesquisa)
    const filteredServices = useMemo(() => {
        if (!searchTerm) return services;
        return (services || []).filter(s => {
            const matchesSearch = (s?.servico ?? s?.descricao ?? '')?.toLowerCase().includes(searchTerm.toLowerCase());
            return matchesSearch;
        });
    }, [services, searchTerm]);

    const handleOpenDialog = (service = null) => {
        if (service) {
            setEditingService(service);
            setFormData({
                servico: service.servico || '',
                valor: service.valor,
                imagem: service.imagem ?? '',
                tipo_servico: service.tipo_servico || 'Serviço'
            });
        } else {
            setEditingService(null);
            setFormData({ servico: '', valor: '', imagem: '', tipo_servico: activeTab });
        }
        setIsDialogOpen(true);
    };

    const handleSave = async () => {
        if (!formData.servico?.trim()) {
            toast.error('Nome é obrigatório', 'Campos Obrigatórios');
            return;
        }
        const valor = Number(formData.valor) || 0;
        if (valor <= 0) {
            toast.error('Valor deve ser maior que zero', 'Validação');
            return;
        }
        setSaving(true);
        try {
            const now = new Date();
            const dataEnvio = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
            const payload = {
                servico: formData.servico.trim(),
                valor,
                imagem: formData.imagem ?? '',
                tipo_servico: formData.tipo_servico
            };
            if (editingService) {
                const ok = await actions?.updateService(editingService.idservicos, payload);
                if (!ok) return;
            } else {
                const ok = await actions?.createService(payload);
                if (!ok) return;
            }
            setIsDialogOpen(false);
            setEditingService(null);
            setFormData({ servico: '', valor: '', imagem: '', tipo_servico: activeTab });
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id) => {
        if (!window.confirm('Tem certeza que deseja excluir?')) return;
        setDeletingId(id);
        try {
            const ok = await actions?.deleteService(id);
            if (!ok) return;
        } finally {
            setDeletingId(null);
        }
    };



    return (
        <div className="space-y-6 animate-in fade-in duration-700">
            <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl dark:shadow-2xl relative overflow-hidden">
                <div className="absolute -top-24 -right-24 w-64 h-64 bg-purple-500/10 dark:bg-purple-500/5 rounded-full blur-3xl pointer-events-none" />
                
                <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 relative z-10">
                    <div className="flex items-center gap-4 w-full sm:w-auto">
                        <div className="w-10 h-10 rounded-xl bg-purple-100 dark:bg-purple-500/10 flex items-center justify-center border border-purple-200 dark:border-purple-500/20 shrink-0">
                            <Server className="w-5 h-5 text-purple-600 dark:text-purple-500" />
                        </div>
                        <div className="flex-1 min-w-0">
                            <h3 className="font-bold text-slate-900 dark:text-white flex items-center gap-2 flex-wrap">
                                Catálogo
                                <Badge variant="outline" className="text-[10px] border-slate-200 dark:border-slate-700 text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-900/50">
                                    {filteredServices.length} ITEMS
                                </Badge>
                            </h3>
                            <p className="text-[10px] text-slate-500 dark:text-slate-500 font-medium uppercase tracking-wider hidden sm:block">Gerenciamento de serviços e produtos</p>
                        </div>
                    </div>
                    
                    <div className="flex items-center gap-3 w-full sm:w-auto">
                        <div className="relative group flex-1 sm:flex-none">
                            <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-slate-500 group-focus-within:text-purple-500 transition-colors" />
                            <Input 
                                placeholder="Buscar..." 
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="bg-slate-50 dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 w-full sm:w-64 pl-9 h-9 text-xs text-slate-900 dark:text-white placeholder:text-slate-500 dark:placeholder:text-slate-600 focus:border-purple-500/50 transition-all rounded-lg"
                            />
                        </div>
                        <Button 
                            size="sm" 
                            className="bg-purple-600 hover:bg-purple-700 text-white font-bold text-xs shrink-0 shadow-lg shadow-purple-500/20 px-3 sm:px-4 h-9"
                            onClick={() => handleOpenDialog()}
                        >
                            <Plus className="w-3.5 h-3.5 sm:mr-2" /> 
                            <span className="hidden sm:inline">Novo</span>
                            <span className="sm:hidden">Novo</span>
                        </Button>
                    </div>
                </CardHeader>
                
                <CardContent className="p-0 relative z-10">
                    <div className="p-4 pb-0">
                         <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                            <TabsList className="grid w-full sm:w-[600px] grid-cols-3">
                                <TabsTrigger value="Serviço" className="gap-2">
                                    <Wrench className="w-4 h-4" /> Serviços
                                </TabsTrigger>
                                <TabsTrigger value="Produto" className="gap-2">
                                    <Package className="w-4 h-4" /> Produtos
                                </TabsTrigger>
                                <TabsTrigger value="Sem Tipo" className="gap-2">
                                    <HelpCircle className="w-4 h-4" /> Sem Tipo
                                </TabsTrigger>
                            </TabsList>
                        </Tabs>
                    </div>

                    {isLoading && (
                        <div className="flex items-center justify-center py-12 gap-2 text-slate-500">
                            <Loader2 className="w-5 h-5 animate-spin" />
                            <span className="text-sm">Carregando...</span>
                        </div>
                    )}
                    {!isLoading && (
                    <>
                    {/* Desktop Table View */}
                    <div className="hidden md:block overflow-x-auto mt-4">
                        <Table>
                            <TableHeader className="bg-slate-50 dark:bg-slate-900/80 sticky top-0">
                                <TableRow className="border-slate-200 dark:border-slate-800 hover:bg-transparent">
                                    <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 w-[60px] pl-6">ID</TableHead>
                                    <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 w-[56px]">Ícone</TableHead>
                                    <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Nome</TableHead>
                                    <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Tipo</TableHead>
                                    <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right">Valor</TableHead>
                                    <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right pr-6">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {filteredServices.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="h-40 text-center text-slate-500 text-sm font-medium">
                                            {searchTerm ? 'Nenhum item encontrado.' : 'Nenhum item cadastrado.'}
                                        </TableCell>
                                    </TableRow>
                                ) : filteredServices.map((service, index) => (
                                    <TableRow key={`${service.idservicos}-${index}`} className="border-slate-200 dark:border-slate-800/50 hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-all duration-200 group">
                                        <TableCell className="font-mono text-xs text-slate-500 dark:text-slate-300 font-medium py-4 pl-6">
                                            #{service.idservicos}
                                        </TableCell>
                                        <TableCell className="py-4">
                                            <ServicoIcon imagem={service.imagem} />
                                        </TableCell>
                                        <TableCell className="py-4">
                                            <div className="flex items-center gap-2">
                                                <span className="text-sm text-slate-900 dark:text-white font-bold tracking-tight">{service.servico || 'Sem nome'}</span>
                                            </div>
                                        </TableCell>
                                        <TableCell className="py-4">
                                             <Badge 
                                                variant="outline" 
                                                className={cn(
                                                    "text-[10px] font-bold border-0",
                                                    service.tipo_servico === 'Produto' 
                                                        ? "bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400" 
                                                        : service.tipo_servico === 'Sem Tipo'
                                                        ? "bg-amber-50 text-amber-600 dark:bg-amber-500/10 dark:text-amber-400"
                                                        : "bg-purple-50 text-purple-600 dark:bg-purple-500/10 dark:text-purple-400"
                                                )}
                                             >
                                                {service.tipo_servico || 'Serviço'}
                                             </Badge>
                                        </TableCell>
                                        <TableCell className="font-mono text-xs font-bold text-purple-600 dark:text-purple-400 text-right py-4">
                                            {formatCurrency(service.valor)}
                                        </TableCell>
                                        <TableCell className="py-4 text-right pr-6">
                                            <div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-all duration-300 translate-x-2 group-hover:translate-x-0">
                                                <Button 
                                                    variant="ghost" 
                                                    size="icon" 
                                                    className="h-8 w-8 text-slate-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-slate-800 rounded-lg"
                                                    onClick={() => handleOpenDialog(service)}
                                                >
                                                    <Edit className="w-3.5 h-3.5" />
                                                </Button>
                                                <Button 
                                                    variant="ghost" 
                                                    size="icon" 
                                                    className="h-8 w-8 text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-slate-800 rounded-lg disabled:opacity-50"
                                                    onClick={() => handleDelete(service.idservicos)}
                                                    disabled={deletingId === service.idservicos}
                                                >
                                                    {deletingId === service.idservicos ? (
                                                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                                    ) : (
                                                        <Trash2 className="w-3.5 h-3.5" />
                                                    )}
                                                </Button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>

                    {/* Mobile Card View */}
                    <div className="md:hidden p-4 space-y-3">
                        {filteredServices.length === 0 ? (
                            <div className="text-center py-12 text-slate-500 text-sm">
                                {searchTerm ? 'Nenhum item encontrado.' : 'Nenhum item cadastrado.'}
                            </div>
                        ) : filteredServices.map((service, index) => (
                            <div
                                key={`${service.idservicos}-${index}`}
                                className="p-4 rounded-xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/30 hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-all"
                            >
                                <div className="flex items-start justify-between gap-3 mb-2">
                                    <div className="flex items-center gap-3 flex-1 min-w-0">
                                        <ServicoIcon imagem={service.imagem} className="w-10 h-10" />
                                        <div className="flex-1 min-w-0">
                                            <h4 className="text-sm font-bold text-slate-900 dark:text-white truncate">{service.servico || 'Sem nome'}</h4>
                                            <Badge variant="outline" className="text-[10px] mt-1">
                                                {service.tipo_servico || 'Serviço'}
                                            </Badge>
                                        </div>
                                    </div>
                                    <div className="text-right shrink-0">
                                        <p className="text-sm font-bold text-purple-600 dark:text-purple-400">{formatCurrency(service.valor)}</p>
                                    </div>
                                </div>
                                <div className="flex justify-end gap-2 pt-2 border-t border-slate-200 dark:border-slate-800">
                                    <Button 
                                        size="sm" 
                                        variant="ghost" 
                                        className="h-8 text-slate-400 hover:text-blue-500"
                                        onClick={() => handleOpenDialog(service)}
                                    >
                                        <Edit className="w-3.5 h-3.5 mr-2" /> Editar
                                    </Button>
                                    <Button 
                                        size="sm" 
                                        variant="ghost" 
                                        className="h-8 text-slate-400 hover:text-red-500 disabled:opacity-50"
                                        onClick={() => handleDelete(service.idservicos)}
                                        disabled={deletingId === service.idservicos}
                                    >
                                        {deletingId === service.idservicos ? (
                                            <Loader2 className="w-3.5 h-3.5 mr-2 animate-spin" /> 
                                        ) : (
                                            <Trash2 className="w-3.5 h-3.5 mr-2" />
                                        )}{' '}
                                        Excluir
                                    </Button>
                                </div>
                            </div>
                        ))}
                    </div>
                    </>
                    )}
                </CardContent>
            </Card>

            {/* Dialog de Criação/Edição */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white">
                    <DialogHeader>
                        <DialogTitle className="text-slate-900 dark:text-white font-bold text-lg">
                            {editingService ? 'Editar Item' : 'Novo Item'}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        
                        <div className="space-y-3">
                            <Label className="text-slate-700 dark:text-slate-300 text-xs font-bold uppercase tracking-wider">
                                Tipo
                            </Label>
                            <RadioGroup 
                                value={formData.tipo_servico} 
                                onValueChange={(val) => setFormData({ ...formData, tipo_servico: val })}
                                className="flex gap-4"
                            >
                                <div className="flex items-center space-x-2">
                                    <RadioGroupItem value="Serviço" id="r-servico" />
                                    <Label htmlFor="r-servico">Serviço</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <RadioGroupItem value="Produto" id="r-produto" />
                                    <Label htmlFor="r-produto">Produto</Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <RadioGroupItem value="Sem Tipo" id="r-sem-tipo" />
                                    <Label htmlFor="r-sem-tipo">Sem Tipo</Label>
                                </div>
                            </RadioGroup>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="servico" className="text-slate-700 dark:text-slate-300 text-xs font-bold uppercase tracking-wider">
                                    Nome
                                </Label>
                                <Input
                                    id="servico"
                                    value={formData.servico}
                                    onChange={(e) => setFormData({ ...formData, servico: e.target.value })}
                                    className="bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-white focus:border-purple-500"
                                    placeholder="Ex: Suporte Técnico"
                                />
                            </div>
                            <CurrencyInput 
                                label="Valor (R$)"
                                value={formData.valor}
                                onChange={(v) => setFormData({ ...formData, valor: v })}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label className="text-slate-700 dark:text-slate-300 text-xs font-bold uppercase tracking-wider block mb-2">
                                Ícone
                            </Label>
                            <IconPicker
                                value={formData.imagem}
                                onChange={(v) => setFormData({ ...formData, imagem: v })}
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button 
                            variant="ghost" 
                            onClick={() => setIsDialogOpen(false)}
                            disabled={saving}
                            className="text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white"
                        >
                            Cancelar
                        </Button>
                        <Button 
                            onClick={handleSave}
                            disabled={saving || !formData.servico?.trim()}
                            className="bg-purple-600 hover:bg-purple-700 text-white disabled:bg-slate-200 dark:disabled:bg-slate-700 disabled:text-slate-400 disabled:cursor-not-allowed"
                        >
                            {saving ? (
                                <>
                                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                    {editingService ? 'Salvando...' : 'Criando...'}
                                </>
                            ) : (
                                <>
                                    <Save className="w-4 h-4 mr-2" />
                                    {editingService ? 'Salvar' : 'Criar'}
                                </>
                            )}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
};
