"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { 
    Plus, 
    Search, 
    Loader2, 
    RefreshCw, 
    Building2, 
    CheckCircle, 
    XCircle, 
    Eye, 
    Trash2, 
    Pencil, 
    ChevronLeft, 
    ChevronRight,
    Users,
    ShieldCheck,
    AlertCircle
} from "lucide-react"
import { Switch } from "@/components/ui/switch"
import { adminCompaniesApi, type AdminCompany } from "@/lib/api"
import { getCurrentUser, isAdminUser } from "@/lib/auth"
import { toast } from "sonner"
import { ConfirmModal } from "@/components/confirm-modal"
import { Skeleton } from "@/components/ui/skeleton"
import { useTranslation } from "@/lib/i18n"
import { motion } from "framer-motion"

const companyDateFormatter = new Intl.DateTimeFormat("pt-BR", {
    dateStyle: "medium",
})

const formatDescription = (description: string | undefined) => {
    if (!description) return null
    try {
        const parsed = JSON.parse(description)
        if (typeof parsed === 'object' && parsed !== null) {
            return (
                <dl className="space-y-2">
                    {Object.entries(parsed).map(([key, value]) => (
                        <div key={key} className="flex flex-col">
                            <dt className="text-xs text-muted-foreground capitalize">
                                {key.replace(/([A-Z])/g, ' $1').replace(/_/g, ' ')}
                            </dt>
                            <dd className="text-sm font-medium">{String(value)}</dd>
                        </div>
                    ))}
                </dl>
            )
        }
    } catch { }
    return <p className="text-sm mt-1">{description}</p>
}

export default function AdminCompaniesPage() {
    const { t } = useTranslation()
    const router = useRouter()
    const [companies, setCompanies] = useState<AdminCompany[]>([])
    const [loading, setLoading] = useState(true)
    const [searchTerm, setSearchTerm] = useState("")
    const [page, setPage] = useState(1)
    const [totalCompanies, setTotalCompanies] = useState(0)
    const [isViewDialogOpen, setIsViewDialogOpen] = useState(false)
    const [selectedCompany, setSelectedCompany] = useState<AdminCompany | null>(null)
    const [companyToDelete, setCompanyToDelete] = useState<AdminCompany | null>(null)
    const [updating, setUpdating] = useState(false)
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
    const [editFormData, setEditFormData] = useState({
        name: "",
        slug: "",
        email: "",
        phone: "",
        website: "",
        document: "",
        address: "",
        description: "",
        logoUrl: "",
        yearsInMarket: "",
        active: false,
        verified: false,
    })

    useEffect(() => {
        const user = getCurrentUser()
        if (!isAdminUser(user)) {
            router.push("/dashboard")
            return
        }
        loadCompanies()
    }, [router])

    const limit = 10
    const totalPages = Math.max(1, Math.ceil(totalCompanies / limit))

    const loadCompanies = async (targetPage = page) => {
        const pageNum = typeof targetPage === 'number' ? targetPage : page
        try {
            setLoading(true)
            const data = await adminCompaniesApi.list(undefined, pageNum, limit)
            setCompanies(data.data || [])
            setTotalCompanies(data.pagination.total)
            setPage(data.pagination.page)
        } catch (error) {
            console.error("Error loading companies:", error)
            toast.error("Erro ao carregar empresas")
        } finally {
            setLoading(false)
        }
    }

    const toggleStatus = async (company: AdminCompany, field: 'active' | 'verified') => {
        const newValue = !company[field]
        const originalCompanies = [...companies]
        setCompanies(companies.map(c => c.id === company.id ? { ...c, [field]: newValue } : c))
        try {
            await adminCompaniesApi.updateStatus(company.id, { [field]: newValue })
            toast.success(t('admin.companies.success.statusUpdated', { field }))
        } catch (error) {
            toast.error(`Falha ao atualizar ${field}`)
            setCompanies(originalCompanies)
        }
    }

    const confirmDelete = async () => {
        if (!companyToDelete) return
        try {
            await adminCompaniesApi.delete(companyToDelete.id)
            toast.success(t('admin.companies.success.deleted'))
            setIsViewDialogOpen(false)
            loadCompanies()
        } catch (error) {
            toast.error("Falha ao deletar empresa")
        } finally {
            setCompanyToDelete(null)
        }
    }

    const handleEditClick = (company: AdminCompany) => {
        setEditFormData({
            name: company.name || "",
            slug: company.slug || "",
            email: company.email || "",
            phone: company.phone || "",
            website: company.website || "",
            document: company.document || "",
            address: company.address || "",
            description: company.description || "",
            logoUrl: (company as any).logoUrl || "",
            yearsInMarket: (company as any).yearsInMarket || "",
            active: company.active || false,
            verified: company.verified || false,
        })
        setIsEditDialogOpen(true)
        setIsViewDialogOpen(false)
    }

    const handleUpdate = async () => {
        if (!selectedCompany) return
        try {
            setUpdating(true)
            if (editFormData.active !== selectedCompany.active || editFormData.verified !== selectedCompany.verified) {
                await adminCompaniesApi.updateStatus(selectedCompany.id, {
                    active: editFormData.active,
                    verified: editFormData.verified
                })
            }
            await adminCompaniesApi.update(selectedCompany.id, editFormData as any)
            toast.success("Empresa atualizada com sucesso")
            setIsEditDialogOpen(false)
            loadCompanies()
        } catch (error) {
            toast.error("Erro ao atualizar empresa")
        } finally {
            setUpdating(false)
        }
    }

    const filteredCompanies = companies.filter(
        (company) =>
            company.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
            company.email?.toLowerCase().includes(searchTerm.toLowerCase())
    )

    return (
        <div className="container py-8 space-y-8">
            {/* Header */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }}>
                    <h1 className="text-4xl font-extrabold tracking-tight">{t('admin.companies.title')}</h1>
                    <p className="text-muted-foreground text-lg">{t('admin.companies.subtitle')}</p>
                </motion.div>
                <div className="flex items-center gap-3">
                    <Button variant="outline" size="lg" onClick={() => loadCompanies()} disabled={loading} className="shadow-sm">
                        <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
                        {t('admin.companies.refresh')}
                    </Button>
                    <Button size="lg" className="gap-2 shadow-md hover:shadow-lg transition-all" asChild>
                        <Link href="/dashboard/companies/new">
                            <Plus className="h-5 w-5" />
                            {t('admin.companies.newCompany')}
                        </Link>
                    </Button>
                </div>
            </div>

            {/* Stats Cards */}
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                <Card className="border-l-4 border-l-blue-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Total de Empresas</CardTitle>
                        <Building2 className="h-4 w-4 text-blue-500" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{totalCompanies}</div>
                    </CardContent>
                </Card>
                <Card className="border-l-4 border-l-green-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Ativas</CardTitle>
                        <CheckCircle className="h-4 w-4 text-green-500" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{companies.filter(c => c.active).length}</div>
                    </CardContent>
                </Card>
                <Card className="border-l-4 border-l-indigo-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Verificadas</CardTitle>
                        <ShieldCheck className="h-4 w-4 text-indigo-500" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{companies.filter(c => c.verified).length}</div>
                    </CardContent>
                </Card>
                <Card className="border-l-4 border-l-amber-500 shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
                        <CardTitle className="text-sm font-medium">Pendentes</CardTitle>
                        <AlertCircle className="h-4 w-4 text-amber-500" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{companies.filter(c => !c.verified).length}</div>
                    </CardContent>
                </Card>
            </div>

            {/* Content Card */}
            <Card className="border-0 shadow-xl overflow-hidden bg-card/50 backdrop-blur-sm">
                <CardHeader className="border-b bg-muted/30">
                    <div className="flex items-center gap-4">
                        <div className="relative flex-1">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input
                                placeholder={t('admin.companies.searchPlaceholder')}
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="pl-10 h-11 border-muted-foreground/20 focus:ring-primary"
                            />
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    {loading ? (
                        <div className="p-8 space-y-4">
                            {[...Array(5)].map((_, i) => <Skeleton key={i} className="h-16 w-full rounded-lg" />)}
                        </div>
                    ) : (
                        <Table>
                            <TableHeader className="bg-muted/50">
                                <TableRow>
                                    <TableHead className="w-[300px] font-bold">Empresa</TableHead>
                                    <TableHead className="font-bold">E-mail</TableHead>
                                    <TableHead className="font-bold">Status</TableHead>
                                    <TableHead className="font-bold">Verificado</TableHead>
                                    <TableHead className="font-bold">Cadastro</TableHead>
                                    <TableHead className="text-right font-bold">Ações</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {filteredCompanies.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="text-center py-20 text-muted-foreground">
                                            Nenhuma empresa encontrada
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    filteredCompanies.map((company) => (
                                        <TableRow key={company.id} className="hover:bg-muted/30 transition-colors">
                                            <TableCell className="font-semibold text-foreground">
                                                <div className="flex items-center gap-3">
                                                    <div className="p-2 bg-primary/5 rounded-lg">
                                                        <Building2 className="h-5 w-5 text-primary" />
                                                    </div>
                                                    {company.name}
                                                </div>
                                            </TableCell>
                                            <TableCell className="text-muted-foreground">{company.email || "-"}</TableCell>
                                            <TableCell>
                                                <Badge
                                                    variant={company.active ? "default" : "secondary"}
                                                    className="cursor-pointer transition-all active:scale-95"
                                                    onClick={() => toggleStatus(company, 'active')}
                                                >
                                                    {company.active ? "Ativo" : "Inativo"}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>
                                                <div
                                                    className="cursor-pointer hover:bg-muted p-1 rounded-full inline-flex transition-colors"
                                                    onClick={() => toggleStatus(company, 'verified')}
                                                >
                                                    {company.verified ? (
                                                        <CheckCircle className="h-6 w-6 text-green-500" />
                                                    ) : (
                                                        <XCircle className="h-6 w-6 text-muted-foreground/40" />
                                                    )}
                                                </div>
                                            </TableCell>
                                            <TableCell className="text-muted-foreground font-medium">
                                                {company.createdAt ? companyDateFormatter.format(new Date(company.createdAt)) : "-"}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <div className="flex items-center justify-end gap-1">
                                                    <Button variant="ghost" size="icon" onClick={() => { setSelectedCompany(company); setIsViewDialogOpen(true); }} className="hover:text-primary">
                                                        <Eye className="h-5 w-5" />
                                                    </Button>
                                                    <Button variant="ghost" size="icon" onClick={() => handleEditClick(company)} className="hover:text-blue-600">
                                                        <Pencil className="h-5 w-5" />
                                                    </Button>
                                                    <Button variant="ghost" size="icon" className="hover:text-destructive hover:bg-destructive/10" onClick={() => setCompanyToDelete(company)}>
                                                        <Trash2 className="h-5 w-5" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    )}
                    
                    {/* Pagination */}
                    {!loading && totalPages > 1 && (
                        <div className="p-4 border-t bg-muted/10 flex items-center justify-between">
                            <p className="text-sm text-muted-foreground font-medium">
                                Mostrando <span className="text-foreground">{(page - 1) * limit + 1}</span> a <span className="text-foreground">{Math.min(page * limit, totalCompanies)}</span> de <span className="text-foreground">{totalCompanies}</span> empresas
                            </p>
                            <div className="flex gap-2">
                                <Button variant="outline" size="sm" onClick={() => loadCompanies(page - 1)} disabled={page <= 1}>
                                    <ChevronLeft className="h-4 w-4 mr-1" /> Anterior
                                </Button>
                                <Button variant="outline" size="sm" onClick={() => loadCompanies(page + 1)} disabled={page >= totalPages}>
                                    Próxima <ChevronRight className="h-4 w-4 ml-1" />
                                </Button>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            <ConfirmModal
                isOpen={!!companyToDelete}
                onClose={() => setCompanyToDelete(null)}
                onConfirm={confirmDelete}
                title="Excluir Empresa"
                description={`Tem certeza que deseja excluir ${companyToDelete?.name}? Esta ação não pode ser desfeita.`}
            />
        </div>
    )
}
