import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../services/api';
import { useAuth } from '../context/useAuth';
import { LayoutDashboard, User } from 'lucide-react';
import type { Project, PaintingScheme } from '../types';
import { ColorBubble } from '../components/ColorBubble';

interface DashboardProject extends Project {
    schemes: (Partial<PaintingScheme> & { colorHex?: string })[];
    paintedWeight?: number;
}

export const GuestDashboard: React.FC = () => {
    const [projects, setProjects] = useState<DashboardProject[]>([]);
    const [loading, setLoading] = useState(true);
    useAuth();
    const navigate = useNavigate();

    useEffect(() => {
        const fetchProjects = async () => {
            try {
                const response = await api.get('/projects/dashboard');
                setProjects(response.data);
            } catch (error) {
                console.error('Error fetching dashboard projects:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchProjects();
    }, []);

    if (loading) {
        return (
            <div className="flex justify-center items-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
        );
    }

    return (
        <div className="space-y-8 animate-in fade-in duration-700">
            {/* Header */}
            <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-2xl bg-indigo-500/10 flex items-center justify-center text-indigo-500 shadow-sm">
                    <LayoutDashboard className="w-6 h-6" />
                </div>
                <div>
                    <h1 className="text-3xl md:text-4xl font-black text-text-main tracking-tight mb-0">Painel Principal</h1>
                    <p className="text-sm text-text-muted font-medium tracking-wide">Visão geral das obras e esquemas ativos</p>
                </div>
            </div>

            {/* Projects Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                {projects.map((project) => (
                    <div key={project.id} className="group relative">
                        {/* Card Background Bloom Effect */}
                        <div className="absolute -inset-1 bg-gradient-to-br from-primary/20 via-transparent to-blue-500/10 rounded-[32px] blur-xl opacity-0 group-hover:opacity-100 transition-all duration-700"></div>

                        <div
                            onClick={() => navigate(`/project/${project.id}`)}
                            className="p-0 flex flex-col h-full relative overflow-hidden bg-surface border border-border/40 rounded-[32px] group-hover:border-primary/40 transition-all duration-500 shadow-soft group-hover:shadow-2xl cursor-pointer"
                        >
                            {/* Header Section */}
                            <div className="p-8 pb-4 relative">
                                <div className="flex justify-between items-start mb-6">
                                    <div className="flex flex-col gap-2">
                                        <span className="text-[10px] font-black text-primary uppercase tracking-[0.25em]">{project.client || 'CLIENTE N/D'}</span>
                                        <h3 className="text-2xl font-black text-text-main tracking-tighter leading-none group-hover:text-primary transition-colors" title={project.name}>
                                            {project.name}
                                        </h3>
                                    </div>
                                </div>

                                <div className="flex flex-wrap gap-2 mb-4">
                                    <span className="px-3 py-1 bg-primary/10 text-primary text-[9px] font-black uppercase tracking-widest rounded-full border border-primary/20">
                                        OBRA ATIVA
                                    </span>
                                    {project.technician && (
                                        <span className="px-3 py-1 bg-surface-highlight text-text-secondary text-[9px] font-black uppercase tracking-widest rounded-full border border-border/50">
                                            RESP: {project.technician}
                                        </span>
                                    )}
                                </div>
                            </div>

                            {/* Body Section */}
                            <div className="px-8 space-y-5 flex-1">
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="p-4 bg-surface-soft/50 rounded-2xl border border-border/20 flex flex-col">
                                        <span className="text-[9px] text-text-muted font-bold uppercase tracking-wider mb-1">Peso Total</span>
                                        <span className="text-xl font-black text-text-main">
                                            {project.weightKg ? Number(project.weightKg).toLocaleString('pt-BR') : '0'} <span className="text-[9px] text-text-muted">kg</span>
                                        </span>
                                    </div>
                                    <div className="p-4 bg-surface-soft/50 rounded-2xl border border-border/20 flex flex-col">
                                        <span className="text-[9px] text-text-muted font-bold uppercase tracking-wider mb-1">Evolução</span>
                                        <span className="text-xl font-black text-text-main">
                                            {project.weightKg && project.paintedWeight !== undefined
                                                ? Math.min(Math.round((project.paintedWeight / project.weightKg) * 100), 100)
                                                : 0}
                                            <span className="text-[9px] text-text-muted">%</span>
                                        </span>
                                    </div>
                                </div>

                                {/* Schemes List */}
                                {project.schemes && project.schemes.length > 0 && (
                                    <div className="py-1">
                                        <div className="text-[10px] font-bold text-text-muted uppercase tracking-widest border-b border-border/40 pb-2 mb-3">Esquemas de Pintura</div>
                                        <div className="space-y-2">
                                            {project.schemes.slice(0, 2).map((scheme, index) => (
                                                <div key={index} className="p-3 bg-surface-soft/50 rounded-xl border border-border/20">
                                                    <div className="flex items-start justify-between gap-2">
                                                        <div className="flex-1 min-w-0">
                                                            <div className="text-[10px] font-black text-primary uppercase tracking-wide mb-1">
                                                                {scheme.coat || scheme.type || 'Camada'}
                                                            </div>
                                                            <div className="text-sm font-black text-text-main line-clamp-1 mb-1.5">
                                                                {scheme.name}
                                                            </div>

                                                            {/* Info Row: Cor */}
                                                            {scheme.color && (
                                                                <div className="flex items-center gap-1 mb-1.5">
                                                                    <span className="w-1 h-1 rounded-full bg-text-muted opacity-50"></span>
                                                                    <span className="text-[13px] font-bold text-text-muted">
                                                                        Cor: {scheme.color}
                                                                    </span>
                                                                </div>
                                                            )}

                                                            {/* Info Row: EPS e Diluente */}
                                                            <div className="flex flex-wrap items-center gap-2">
                                                                {(scheme.epsMin || scheme.epsMax) && (
                                                                    <span className="font-mono bg-primary/5 text-primary px-2 py-1 rounded border border-primary/10 font-bold text-[13px]">
                                                                        EPS: {scheme.epsMin}-{scheme.epsMax}µm
                                                                    </span>
                                                                )}
                                                                {scheme.thinnerSymbol && (
                                                                    <span className="px-2 py-1 bg-surface-highlight text-text-secondary rounded border border-border/50 font-bold text-[13px]">
                                                                        {scheme.thinnerSymbol}
                                                                    </span>
                                                                )}
                                                            </div>
                                                        </div>
                                                        {scheme.colorHex && (
                                                            <ColorBubble colorHex={scheme.colorHex} className="w-6 h-6 shadow-md flex-shrink-0" />
                                                        )}
                                                    </div>
                                                </div>
                                            ))}
                                            {project.schemes.length > 2 && (
                                                <div className="text-[9px] text-center text-primary font-black bg-primary/5 py-1.5 rounded border border-primary/10">
                                                    + {project.schemes.length - 2} ESQUEMAS ADICIONAIS
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>

                            {/* Footer Section */}
                            <div className="p-8 pt-6 border-t border-border/40 mt-6 flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="w-8 h-8 rounded-full bg-surface-highlight flex items-center justify-center border border-border/40">
                                        <User size={14} className="text-text-muted" />
                                    </div>
                                    <div className="flex flex-col">
                                        <span className="text-[9px] font-black text-text-muted uppercase tracking-tighter">Responsável</span>
                                        <span className="text-[11px] font-bold text-text-secondary">{project.technician || 'Não Definido'}</span>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2.5 h-10 px-6 bg-surface-highlight hover:bg-primary hover:text-white border border-border/40 rounded-xl text-xs font-black transition-all group/btn">
                                    <LayoutDashboard size={14} className="group-hover/btn:scale-110 transition-transform" />
                                    VER PROJETO
                                </div>
                            </div>
                        </div>
                    </div>
                ))}

                {projects.length === 0 && (
                    <div className="col-span-full py-20 text-center">
                        <div className="mx-auto w-16 h-16 bg-surface-soft rounded-2xl flex items-center justify-center text-text-muted mb-4">
                            <LayoutDashboard size={32} />
                        </div>
                        <h3 className="text-xl font-bold text-text-main">Nenhum projeto encontrado</h3>
                        <p className="text-text-muted mt-2">Você não possui acesso a nenhum projeto ativo no momento.</p>
                    </div>
                )}
            </div>
        </div>
    );
};
