import { useEffect, useState } from 'react'
import { Shell } from '../layouts/Shell'
import { apiClient } from '../services/apiClient'

interface Company {
    id: string
    role: string
    cnpj: string
    corporate_name: string
    license_number: string
    is_verified: boolean
    created_at: string
}

export function CompanyPage() {
    const [company, setCompany] = useState<Company | null>(null)
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)
    const [editing, setEditing] = useState(false)
    const [form, setForm] = useState({
        corporate_name: '',
        license_number: ''
    })

    useEffect(() => {
        loadCompany()
    }, [])

    const loadCompany = async () => {
        try {
            setLoading(true)
            const response = await apiClient.get('/v1/companies/me')
            setCompany(response.data)
            setForm({
                corporate_name: response.data.corporate_name,
                license_number: response.data.license_number
            })
            setError(null)
        } catch (err) {
            setError('Erro ao carregar dados da empresa')
            console.error(err)
        } finally {
            setLoading(false)
        }
    }

    const saveChanges = async () => {
        if (!company) return
        try {
            await apiClient.put(`/v1/companies/${company.id}`, form)
            await loadCompany()
            setEditing(false)
        } catch (err) {
            console.error('Erro ao salvar:', err)
        }
    }

    const roleLabels: Record<string, string> = {
        pharmacy: 'Farmácia',
        distributor: 'Distribuidora',
        admin: 'Administrador'
    }

    return (
        <Shell>
            <div className="max-w-2xl mx-auto space-y-6">
                <div className="flex items-center justify-between">
                    <h1 className="text-xl font-semibold text-medicalBlue">Minha Empresa</h1>
                    {company && !editing && (
                        <button
                            onClick={() => setEditing(true)}
                            className="rounded bg-medicalBlue px-4 py-2 text-sm font-semibold text-white"
                        >
                            Editar
                        </button>
                    )}
                </div>

                {loading && (
                    <div className="flex justify-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-medicalBlue"></div>
                    </div>
                )}

                {error && (
                    <div className="rounded bg-red-100 p-4 text-red-700">{error}</div>
                )}

                {company && !editing && (
                    <div className="rounded-lg bg-white p-6 shadow-sm space-y-4">
                        <div className="flex items-center justify-between">
                            <span className="text-sm text-gray-500">Status</span>
                            {company.is_verified ? (
                                <span className="rounded bg-green-100 px-3 py-1 text-sm font-semibold text-green-800">
                                    ✓ Verificada
                                </span>
                            ) : (
                                <span className="rounded bg-yellow-100 px-3 py-1 text-sm font-semibold text-yellow-800">
                                    Pendente verificação
                                </span>
                            )}
                        </div>
                        <div className="border-t pt-4 space-y-3">
                            <div>
                                <p className="text-sm text-gray-500">Razão Social</p>
                                <p className="font-semibold text-gray-800">{company.corporate_name}</p>
                            </div>
                            <div>
                                <p className="text-sm text-gray-500">CNPJ</p>
                                <p className="font-semibold text-gray-800">{company.cnpj}</p>
                            </div>
                            <div>
                                <p className="text-sm text-gray-500">Tipo</p>
                                <p className="font-semibold text-gray-800">{roleLabels[company.role] || company.role}</p>
                            </div>
                            <div>
                                <p className="text-sm text-gray-500">Licença Sanitária</p>
                                <p className="font-semibold text-gray-800">{company.license_number}</p>
                            </div>
                            <div>
                                <p className="text-sm text-gray-500">Cadastro</p>
                                <p className="font-semibold text-gray-800">
                                    {new Date(company.created_at).toLocaleDateString('pt-BR')}
                                </p>
                            </div>
                        </div>
                    </div>
                )}

                {company && editing && (
                    <div className="rounded-lg bg-white p-6 shadow-sm space-y-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Razão Social
                            </label>
                            <input
                                type="text"
                                value={form.corporate_name}
                                onChange={(e) => setForm({ ...form, corporate_name: e.target.value })}
                                className="w-full rounded border border-gray-200 px-3 py-2"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Licença Sanitária
                            </label>
                            <input
                                type="text"
                                value={form.license_number}
                                onChange={(e) => setForm({ ...form, license_number: e.target.value })}
                                className="w-full rounded border border-gray-200 px-3 py-2"
                            />
                        </div>
                        <div className="flex gap-3">
                            <button
                                onClick={saveChanges}
                                className="rounded bg-healthGreen px-4 py-2 text-sm font-semibold text-white"
                            >
                                Salvar
                            </button>
                            <button
                                onClick={() => setEditing(false)}
                                className="rounded bg-gray-200 px-4 py-2 text-sm font-semibold text-gray-700"
                            >
                                Cancelar
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </Shell>
    )
}
