"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
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,
    DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Plus, Search, Loader2, RefreshCw, Building2, CheckCircle, XCircle, Eye, Trash2, Pencil } 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 { Skeleton } from "@/components/ui/skeleton"

const companyDateFormatter = new Intl.DateTimeFormat("en-US", {
    dateStyle: "medium",
    timeZone: "UTC",
})

// Helper to format description (handles JSON or plain text)
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">{String(value)}</dd>
                        </div>
                    ))}
                </dl>
            )
        }
    } catch {
        // Not JSON, return as plain text
    }

    return <p className="text-sm mt-1">{description}</p>
}

export default function AdminCompaniesPage() {
    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 [isDialogOpen, setIsDialogOpen] = useState(false)
    const [isViewDialogOpen, setIsViewDialogOpen] = useState(false)
    const [selectedCompany, setSelectedCompany] = useState<AdminCompany | null>(null)
    const [creating, setCreating] = useState(false)
    const [updating, setUpdating] = useState(false)
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
    const [formData, setFormData] = useState({
        name: "",
        slug: "",
        email: "",
    })
    const [editFormData, setEditFormData] = useState({
        name: "",
        slug: "",
        email: "",
        phone: "",
        website: "",
        document: "",
        address: "",
        description: "",
        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) => {
        // If coming from onClick event, targetPage might be the event object
        // Ensure it is a number
        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("Failed to load companies")
        } finally {
            setLoading(false)
        }
    }

    const handleCreate = async () => {
        try {
            setCreating(true)
            await adminCompaniesApi.create(formData)
            toast.success("Company created successfully!")
            setIsDialogOpen(false)
            setFormData({ name: "", slug: "", email: "" })
            loadCompanies(1) // Reload first page
        } catch (error) {
            console.error("Error creating company:", error)
            toast.error("Failed to create company")
        } finally {
            setCreating(false)
        }
    }

    const handleView = (company: AdminCompany) => {
        setSelectedCompany(company)
        setIsViewDialogOpen(true)
    }

    const toggleStatus = async (company: AdminCompany, field: 'active' | 'verified') => {
        const newValue = !company[field]
        // Optimistic update
        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(`Company ${field} updated`)
        } catch (error) {
            toast.error(`Failed to update ${field}`)
            setCompanies(originalCompanies)
        }
    }

    const generateSlug = (name: string) => {
        return name
            .toLowerCase()
            .normalize("NFD")
            .replace(/[\u0300-\u036f]/g, "")
            .replace(/[^a-z0-9]+/g, "-")
            .replace(/(^-|-$)/g, "")
    }

    const handleDelete = async (company: AdminCompany) => {
        if (!window.confirm(`Are you sure you want to delete ${company.name}? This action cannot be undone.`)) return

        try {
            await adminCompaniesApi.delete(company.id)
            toast.success("Company deleted successfully")
            setIsViewDialogOpen(false)
            loadCompanies()
        } catch (error) {
            console.error("Error deleting company:", error)
            toast.error("Failed to delete company")
        }
    }

    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 || "",
            active: company.active || false,
            verified: company.verified || false,
        })
        setIsEditDialogOpen(true)
        setIsViewDialogOpen(false)
    }

    const handleUpdate = async () => {
        if (!selectedCompany) return
        try {
            setUpdating(true)

            // Check if status changed
            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, {
                name: editFormData.name,
                slug: editFormData.slug,
                email: editFormData.email,
                phone: editFormData.phone,
                website: editFormData.website,
                document: editFormData.document,
                address: editFormData.address,
                description: editFormData.description,
            })

            toast.success("Company updated successfully")
            setIsEditDialogOpen(false)
            loadCompanies()
        } catch (error) {
            console.error("Error updating company:", error)
            toast.error("Failed to update company")
        } finally {
            setUpdating(false)
        }
    }

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

    return (
        <div className="space-y-8">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold text-foreground">Company management</h1>
                    <p className="text-muted-foreground mt-1">Manage all registered companies</p>
                </div>
                <div className="flex gap-2">
                    <Button variant="outline" onClick={() => loadCompanies()} disabled={loading}>
                        <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
                        Refresh
                    </Button>
                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                        <DialogTrigger asChild>
                            <Button className="gap-2">
                                <Plus className="h-4 w-4" />
                                New company
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <DialogHeader>
                                <DialogTitle>Create new company</DialogTitle>
                                <DialogDescription>Fill in the company details</DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-4 py-4">
                                <div className="grid gap-2">
                                    <Label htmlFor="name">Company name</Label>
                                    <Input
                                        id="name"
                                        value={formData.name}
                                        onChange={(e) =>
                                            setFormData({
                                                ...formData,
                                                name: e.target.value,
                                                slug: generateSlug(e.target.value),
                                            })
                                        }
                                        placeholder="Company XYZ"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="slug">Slug (URL)</Label>
                                    <Input
                                        id="slug"
                                        value={formData.slug}
                                        onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
                                        placeholder="empresa-xyz"
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="email">Email</Label>
                                    <Input
                                        id="email"
                                        type="email"
                                        value={formData.email}
                                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                        placeholder="hello@company.com"
                                    />
                                </div>
                            </div>
                            <DialogFooter>
                                <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                                <Button onClick={handleCreate} disabled={creating}>
                                    {creating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                                    Create company
                                </Button>
                            </DialogFooter>
                        </DialogContent>
                    </Dialog>
                </div>
            </div>

            {/* Stats */}
            <div className="grid gap-4 md:grid-cols-4">
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Total companies</CardDescription>
                        <CardTitle className="text-3xl">{totalCompanies}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Active companies</CardDescription>
                        <CardTitle className="text-3xl">{companies.filter((c) => c.active).length}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Verified</CardDescription>
                        <CardTitle className="text-3xl">{companies.filter((c) => c.verified).length}</CardTitle>
                    </CardHeader>
                </Card>
                <Card>
                    <CardHeader className="pb-3">
                        <CardDescription>Pending</CardDescription>
                        <CardTitle className="text-3xl">{companies.filter((c) => !c.verified).length}</CardTitle>
                    </CardHeader>
                </Card>
            </div>

            {/* Table */}
            <Card>
                <CardHeader>
                    <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="Search companies by name or email..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="pl-10"
                            />
                        </div>
                    </div>
                </CardHeader>
                <CardContent>
                    {loading ? (
                        <div className="space-y-2 py-4">
                            {[...Array(5)].map((_, i) => (
                                <div key={i} className="flex items-center space-x-4">
                                    <Skeleton className="h-12 w-full" />
                                </div>
                            ))}
                        </div>
                    ) : (
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Company</TableHead>
                                    <TableHead>Email</TableHead>
                                    <TableHead>Status</TableHead>
                                    <TableHead>Verified</TableHead>
                                    <TableHead>Created</TableHead>
                                    <TableHead className="text-right">Actions</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {filteredCompanies.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                                            No companies found
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    filteredCompanies.map((company) => (
                                        <TableRow key={company.id}>
                                            <TableCell className="font-medium">
                                                <div className="flex items-center gap-2">
                                                    <Building2 className="h-4 w-4 text-muted-foreground" />
                                                    {company.name}
                                                </div>
                                            </TableCell>
                                            <TableCell>{company.email || "-"}</TableCell>
                                            <TableCell>
                                                <Badge
                                                    variant={company.active ? "default" : "secondary"}
                                                    className="cursor-pointer hover:opacity-80"
                                                    onClick={() => toggleStatus(company, 'active')}
                                                >
                                                    {company.active ? "Active" : "Inactive"}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>
                                                <div
                                                    className="cursor-pointer hover:opacity-80 inline-flex"
                                                    onClick={() => toggleStatus(company, 'verified')}
                                                >
                                                    {company.verified ? (
                                                        <CheckCircle className="h-5 w-5 text-green-500" />
                                                    ) : (
                                                        <XCircle className="h-5 w-5 text-muted-foreground" />
                                                    )}
                                                </div>
                                            </TableCell>
                                            <TableCell>
                                                {company.createdAt ? companyDateFormatter.format(new Date(company.createdAt)) : "-"}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <Button variant="ghost" size="icon" onClick={() => handleView(company)}>
                                                    <Eye className="h-4 w-4" />
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    )}
                    {!loading && (
                        <div className="flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground mt-4">
                            <span>
                                {totalCompanies === 0
                                    ? "No companies to display"
                                    : `Showing ${(page - 1) * limit + 1}-${Math.min(page * limit, totalCompanies)} of ${totalCompanies}`}
                            </span>
                            <div className="flex items-center gap-2">
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => loadCompanies(page - 1)}
                                    disabled={page <= 1 || loading}
                                >
                                    Previous
                                </Button>
                                <span>
                                    Page {page} of {totalPages}
                                </span>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => loadCompanies(page + 1)}
                                    disabled={page >= totalPages || loading}
                                >
                                    Next
                                </Button>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>
            {/* View Company Modal */}
            <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
                <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <Building2 className="h-5 w-5" />
                            {selectedCompany?.name}
                        </DialogTitle>
                        <DialogDescription>Company details and information</DialogDescription>
                    </DialogHeader>
                    {selectedCompany && (
                        <div className="space-y-6 py-4">
                            {/* Status Badges */}
                            <div className="flex gap-2">
                                <Badge variant={selectedCompany.active ? "default" : "secondary"}>
                                    {selectedCompany.active ? "Active" : "Inactive"}
                                </Badge>
                                <Badge variant={selectedCompany.verified ? "default" : "outline"}>
                                    {selectedCompany.verified ? "Verified" : "Not Verified"}
                                </Badge>
                                {selectedCompany.type && (
                                    <Badge variant="outline">{selectedCompany.type}</Badge>
                                )}
                            </div>

                            {/* Basic Info */}
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <Label className="text-muted-foreground text-xs">Slug</Label>
                                    <p className="font-mono text-sm">{selectedCompany.slug}</p>
                                </div>
                                <div>
                                    <Label className="text-muted-foreground text-xs">Email</Label>
                                    <p className="text-sm">{selectedCompany.email || "-"}</p>
                                </div>
                                <div>
                                    <Label className="text-muted-foreground text-xs">Phone</Label>
                                    <p className="text-sm">{selectedCompany.phone || "-"}</p>
                                </div>
                                <div>
                                    <Label className="text-muted-foreground text-xs">Website</Label>
                                    <p className="text-sm">
                                        {selectedCompany.website ? (
                                            <a
                                                href={selectedCompany.website}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="text-primary hover:underline"
                                            >
                                                {selectedCompany.website}
                                            </a>
                                        ) : (
                                            "-"
                                        )}
                                    </p>
                                </div>
                                <div>
                                    <Label className="text-muted-foreground text-xs">Document (CNPJ)</Label>
                                    <p className="text-sm font-mono">{selectedCompany.document || "-"}</p>
                                </div>
                                <div>
                                    <Label className="text-muted-foreground text-xs">Address</Label>
                                    <p className="text-sm">{selectedCompany.address || "-"}</p>
                                </div>
                            </div>

                            {/* Description */}
                            {selectedCompany.description && (
                                <div>
                                    <Label className="text-muted-foreground text-xs">Description</Label>
                                    <div className="mt-1">
                                        {formatDescription(selectedCompany.description)}
                                    </div>
                                </div>
                            )}

                            {/* Timestamps */}
                            <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                                <div>
                                    <Label className="text-muted-foreground text-xs">Created At</Label>
                                    <p className="text-sm">
                                        {selectedCompany.createdAt
                                            ? companyDateFormatter.format(new Date(selectedCompany.createdAt))
                                            : "-"}
                                    </p>
                                </div>
                                <div>
                                    <Label className="text-muted-foreground text-xs">Updated At</Label>
                                    <p className="text-sm">
                                        {selectedCompany.updatedAt
                                            ? companyDateFormatter.format(new Date(selectedCompany.updatedAt))
                                            : "-"}
                                    </p>
                                </div>
                            </div>
                        </div>
                    )}
                    <DialogFooter className="flex w-full justify-between sm:justify-between">
                        {selectedCompany && (
                            <Button
                                variant="destructive"
                                onClick={() => handleDelete(selectedCompany)}
                            >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Delete
                            </Button>
                        )}
                        <div className="flex gap-2">
                            <Button variant="outline" onClick={() => setIsViewDialogOpen(false)}>
                                Close
                            </Button>
                            {selectedCompany && (
                                <Button onClick={() => handleEditClick(selectedCompany)}>
                                    <Pencil className="h-4 w-4 mr-2" />
                                    Edit
                                </Button>
                            )}
                        </div>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
                <DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Edit company</DialogTitle>
                        <DialogDescription>Update company information</DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">
                        <div className="flex items-center gap-4 border p-4 rounded-md">
                            <div className="flex items-center gap-2">
                                <Switch
                                    checked={editFormData.active}
                                    onCheckedChange={(checked) => setEditFormData({ ...editFormData, active: checked })}
                                    id="edit-active"
                                />
                                <Label htmlFor="edit-active">Active</Label>
                            </div>
                            <div className="flex items-center gap-2">
                                <Switch
                                    checked={editFormData.verified}
                                    onCheckedChange={(checked) => setEditFormData({ ...editFormData, verified: checked })}
                                    id="edit-verified"
                                />
                                <Label htmlFor="edit-verified">Verified</Label>
                            </div>
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-name">Company name</Label>
                            <Input
                                id="edit-name"
                                value={editFormData.name}
                                onChange={(e) => setEditFormData({ ...editFormData, name: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-slug">Slug</Label>
                            <Input
                                id="edit-slug"
                                value={editFormData.slug}
                                onChange={(e) => setEditFormData({ ...editFormData, slug: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-email">Email</Label>
                            <Input
                                id="edit-email"
                                value={editFormData.email}
                                onChange={(e) => setEditFormData({ ...editFormData, email: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-phone">Phone</Label>
                            <Input
                                id="edit-phone"
                                value={editFormData.phone}
                                onChange={(e) => setEditFormData({ ...editFormData, phone: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-website">Website</Label>
                            <Input
                                id="edit-website"
                                value={editFormData.website}
                                onChange={(e) => setEditFormData({ ...editFormData, website: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-document">Document</Label>
                            <Input
                                id="edit-document"
                                value={editFormData.document}
                                onChange={(e) => setEditFormData({ ...editFormData, document: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-address">Address</Label>
                            <Input
                                id="edit-address"
                                value={editFormData.address}
                                onChange={(e) => setEditFormData({ ...editFormData, address: e.target.value })}
                            />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-description">Description</Label>
                            <Input
                                id="edit-description"
                                value={editFormData.description}
                                onChange={(e) => setEditFormData({ ...editFormData, description: e.target.value })}
                            />
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>Cancel</Button>
                        <Button onClick={handleUpdate} disabled={updating}>
                            {updating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                            Save changes
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
