'use client';

import { BuildingOfficeIcon, ArrowLeftIcon, PaintBrushIcon, MapPinIcon } from '@heroicons/react/24/outline';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';

interface AgencyTenant {
    id: string;
    name: string;
    subdomain: string;
    domain: string;
    email: string;
    phone: string;
    website: string;
    cnpj: string;
    razao_social: string;
    description: string;
    industry: string;
    team_size: string;
    address: string;
    neighborhood: string;
    number: string;
    complement: string;
    city: string;
    state: string;
    zip: string;
    primary_color: string;
    secondary_color: string;
    logo_url: string;
    logo_horizontal_url: string;
    is_active: boolean;
    created_at: string;
    updated_at: string;
}

interface AgencyDetails {
    tenant: AgencyTenant;
    admin?: {
        id: string;
        email: string;
        name: string;
    };
    access_url: string;
}

export default function AgencyDetailPage() {
    const params = useParams();
    const [details, setDetails] = useState<AgencyDetails | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (params.id) {
            fetchAgency(params.id as string);
        }
    }, [params.id]);

    const fetchAgency = async (id: string) => {
        try {
            const response = await fetch(`/api/admin/agencies/${id}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                // Handle both flat (legacy) and nested (new) responses
                if (data.tenant) {
                    setDetails(data);
                } else {
                    // Fallback for legacy flat response
                    setDetails({
                        tenant: data,
                        access_url: `http://${data.subdomain}.localhost`, // Fallback URL
                    });
                }
            }
        } catch (error) {
            console.error('Error fetching agency:', error);
        } finally {
            setLoading(false);
        }
    };

    if (loading) {
        return (
            <div className="p-8 flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    if (!details || !details.tenant) {
        return (
            <div className="p-8">
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative" role="alert">
                    <strong className="font-bold">Erro!</strong>
                    <span className="block sm:inline"> Agência não encontrada.</span>
                </div>
                <Link
                    href="/superadmin/agencies"
                    className="mt-4 inline-flex items-center gap-2 text-gray-600 hover:text-gray-900"
                >
                    <ArrowLeftIcon className="w-4 h-4" />
                    Voltar para Agências
                </Link>
            </div>
        );
    }

    const { tenant } = details;

    return (
        <div className="p-8 max-w-7xl mx-auto">
            <div className="mb-8">
                <Link
                    href="/superadmin/agencies"
                    className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200 mb-6 transition-colors"
                >
                    <ArrowLeftIcon className="w-4 h-4" />
                    Voltar para Agências
                </Link>

                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div className="flex items-center gap-4">
                        <div className="h-16 w-16 rounded-xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center p-2">
                            {tenant.logo_url ? (
                                <img src={tenant.logo_url} alt={tenant.name} className="max-h-full max-w-full object-contain" />
                            ) : (
                                <BuildingOfficeIcon className="w-8 h-8 text-gray-400" />
                            )}
                        </div>
                        <div>
                            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{tenant.name}</h1>
                            <div className="flex items-center gap-2 mt-1">
                                <a
                                    href={details.access_url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1"
                                >
                                    {tenant.subdomain}.aggios.app
                                    <ArrowLeftIcon className="w-3 h-3 rotate-135" />
                                </a>
                                <span className="text-gray-300 dark:text-gray-600">|</span>
                                <span className={`px-2 py-0.5 inline-flex text-xs font-medium rounded-full ${tenant.is_active
                                    ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                                    : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
                                    }`}>
                                    {tenant.is_active ? 'Ativa' : 'Inativa'}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div className="flex gap-3">
                        <Link
                            href={`/superadmin/agencies/${tenant.id}/edit`}
                            className="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors font-medium text-sm"
                        >
                            Editar Dados
                        </Link>
                        <button
                            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium text-sm"
                        >
                            Acessar Painel
                        </button>
                    </div>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Coluna Esquerda (2/3) */}
                <div className="lg:col-span-2 space-y-6">
                    {/* Informações Básicas */}
                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
                        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
                            <h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                                <BuildingOfficeIcon className="w-5 h-5 text-gray-500" />
                                Dados da Empresa
                            </h2>
                        </div>
                        <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Razão Social</dt>
                                <dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">{tenant.razao_social || '-'}</dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">CNPJ</dt>
                                <dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">{tenant.cnpj || '-'}</dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Setor</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.industry || '-'}</dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Tamanho da Equipe</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.team_size || '-'}</dd>
                            </div>
                            <div className="md:col-span-2">
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Descrição</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.description || '-'}</dd>
                            </div>
                        </div>
                    </div>

                    {/* Endereço */}
                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
                        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
                            <h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                                <MapPinIcon className="w-5 h-5 text-gray-500" />
                                Localização
                            </h2>
                        </div>
                        <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="md:col-span-2">
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Endereço</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">
                                    {tenant.address ? (
                                        <>
                                            {tenant.address}
                                            {tenant.number ? `, ${tenant.number}` : ''}
                                            {tenant.complement ? ` - ${tenant.complement}` : ''}
                                        </>
                                    ) : '-'}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Bairro</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.neighborhood || '-'}</dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Cidade / UF</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">
                                    {tenant.city && tenant.state ? `${tenant.city} - ${tenant.state}` : '-'}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">CEP</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.zip || '-'}</dd>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Coluna Direita (1/3) */}
                <div className="space-y-6">
                    {/* Branding */}
                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
                        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
                            <h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                                <PaintBrushIcon className="w-5 h-5 text-gray-500" />
                                Identidade Visual
                            </h2>
                        </div>
                        <div className="p-6 space-y-6">
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Cores da Marca</dt>
                                <div className="flex gap-4">
                                    <div className="text-center">
                                        <div
                                            className="w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 mb-1"
                                            style={{ backgroundColor: tenant.primary_color || '#000000' }}
                                        />
                                        <span className="text-xs font-mono text-gray-500">{tenant.primary_color || '-'}</span>
                                    </div>
                                    <div className="text-center">
                                        <div
                                            className="w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 mb-1"
                                            style={{ backgroundColor: tenant.secondary_color || '#ffffff' }}
                                        />
                                        <span className="text-xs font-mono text-gray-500">{tenant.secondary_color || '-'}</span>
                                    </div>
                                </div>
                            </div>

                            {tenant.logo_horizontal_url && (
                                <div>
                                    <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Logo Horizontal</dt>
                                    <div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 flex justify-center">
                                        <img src={tenant.logo_horizontal_url} alt="Logo Horizontal" className="max-h-12 max-w-full object-contain" />
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Contato */}
                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
                        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
                            <h2 className="text-base font-semibold text-gray-900 dark:text-white">
                                Contato
                            </h2>
                        </div>
                        <div className="p-6 space-y-4">
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Email</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white break-all">{tenant.email || '-'}</dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Telefone</dt>
                                <dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.phone || '-'}</dd>
                            </div>
                            <div>
                                <dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Website</dt>
                                <dd className="mt-1">
                                    {tenant.website ? (
                                        <a
                                            href={tenant.website}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="text-sm text-blue-600 dark:text-blue-400 hover:underline break-all"
                                        >
                                            {tenant.website}
                                        </a>
                                    ) : '-'}
                                </dd>
                            </div>
                        </div>
                    </div>

                    {/* Metadados */}
                    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
                        <dl className="space-y-3">
                            <div className="flex justify-between">
                                <dt className="text-sm text-gray-500 dark:text-gray-400">Criada em</dt>
                                <dd className="text-sm font-medium text-gray-900 dark:text-white">
                                    {new Date(tenant.created_at).toLocaleDateString('pt-BR')}
                                </dd>
                            </div>
                            <div className="flex justify-between">
                                <dt className="text-sm text-gray-500 dark:text-gray-400">Última atualização</dt>
                                <dd className="text-sm font-medium text-gray-900 dark:text-white">
                                    {new Date(tenant.updated_at).toLocaleDateString('pt-BR')}
                                </dd>
                            </div>
                        </dl>
                    </div>
                </div>
            </div>
        </div>
    );
}
