"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 } from "lucide-react"
import { adminCompaniesApi, type ApiCompany } 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",
})

export default function AdminCompaniesPage() {
    const router = useRouter()
    const [companies, setCompanies] = useState<ApiCompany[]>([])
    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<ApiCompany | null>(null)
    const [creating, setCreating] = useState(false)
    const [formData, setFormData] = useState({
        name: "",
        slug: "",
        email: "",
    })

    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: ApiCompany) => {
        setSelectedCompany(company)
        setIsViewDialogOpen(true)
    }

    const toggleStatus = async (company: ApiCompany, 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(Number(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 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>Slug</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 className="font-mono text-sm">{company.slug}</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.created_at ? companyDateFormatter.format(new Date(company.created_at)) : "-"}
                                            </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>
        </div>
    )
}
