import { useEffect, useState } from "react"
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import {
    Briefcase,
    Users,
    Eye,
    TrendingUp,
    Plus,
    MoreVertical,
    Calendar,
    MapPin,
    DollarSign,
} from "lucide-react"
import Link from "next/link"
import { jobsApi, applicationsApi, ApiJob } from "@/lib/api"
import { User } from "@/lib/auth"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { useTranslation } from "@/lib/i18n"

interface CompanyDashboardContentProps {
    user: User
}

export function CompanyDashboardContent({ user }: CompanyDashboardContentProps) {
    const { t } = useTranslation()
    const [stats, setStats] = useState({
        activeJobs: 0,
        totalApplications: 0,
        totalViews: 0,
        thisMonth: 0,
    })
    const [recentJobs, setRecentJobs] = useState<ApiJob[]>([])
    const [recentApplications, setRecentApplications] = useState<any[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const fetchData = async () => {
            try {
                // Use user.companyId if available, or fetch current user profile again to be sure?
                // For now assuming user.id is the link or user has companyId property if updated
                // The backend Me handler now returns companyId.
                // We should rely on what's passed.
                // If user doesn't have companyId, we might fail to filter.
                // But let's try passing companyId from user if it exists (we added it to DTO but generic User interface might need update).
                // Casting user to any to access companyId safely
                const companyId = (user as any).companyId?.toString();

                const [jobsRes, appsRes] = await Promise.all([
                    jobsApi.list({ limit: 5, companyId }),
                    applicationsApi.list({ companyId })
                ])

                const jobs = jobsRes.data || []
                const applications = appsRes || []

                setRecentJobs(jobs.slice(0, 5))
                setRecentApplications(applications.slice(0, 5))

                // Calculate Stats
                const activeJobs = jobs.length // This is just page 1. Ideally we get total from pagination
                // But pagination total is in jobsRes.pagination.total
                const totalActive = jobsRes.pagination?.total || 0

                setStats({
                    activeJobs: totalActive,
                    totalApplications: applications.length,
                    totalViews: 0, // Not available yet
                    thisMonth: applications.filter(a => new Date(a.created_at) > new Date(new Date().setDate(1))).length
                })
            } catch (error) {
                console.error("Error fetching dashboard data:", error)
            } finally {
                setLoading(false)
            }
        }

        fetchData()
    }, [user])

    const statusColors: any = {
        pending: "bg-yellow-500",
        reviewing: "bg-blue-500",
        accepted: "bg-green-500",
        rejected: "bg-red-500",
    }

    if (loading) {
        return <div className="p-8 text-center">Carregando dashboard...</div>
    }

    return (
        <div className="space-y-8">
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-2">
                        {t('company.dashboard.title')}
                    </h1>
                    <p className="text-muted-foreground">
                        {t('company.dashboard.welcome', { name: user.name })} 👋
                    </p>
                </div>
                <Link href="/dashboard/my-jobs">
                    <Button size="lg" className="w-full sm:w-auto">
                        <Plus className="h-5 w-5 mr-2" />
                        {t('company.dashboard.new_job')}
                    </Button>
                </Link>
            </div>

            {/* Stats Cards */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">
                            {t('company.dashboard.stats.active_jobs')}
                        </CardTitle>
                        <Briefcase className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">
                            {stats.activeJobs}
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">
                            {t('company.dashboard.stats.posted')}
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">
                            {t('company.dashboard.stats.applications')}
                        </CardTitle>
                        <Users className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">
                            {stats.totalApplications}
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">
                            {t('company.dashboard.stats.this_month', { count: stats.thisMonth })}
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">
                            {t('company.dashboard.stats.views')}
                        </CardTitle>
                        <Eye className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">
                            -
                        </div>
                        <p className="text-xs text-muted-foreground mt-1">
                            {t('company.dashboard.stats.soon')}
                        </p>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">
                            {t('company.dashboard.stats.conversion')}
                        </CardTitle>
                        <TrendingUp className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">-</div>
                        <p className="text-xs text-muted-foreground mt-1">
                            {t('company.dashboard.stats.soon')}
                        </p>
                    </CardContent>
                </Card>
            </div>

            <div className="grid lg:grid-cols-3 gap-6">
                {/* Recent jobs */}
                <div className="lg:col-span-2">
                    <Card>
                        <CardHeader>
                            <div className="flex items-center justify-between">
                                <div>
                                    <CardTitle>{t('company.dashboard.recent_jobs.title')}</CardTitle>
                                    <CardDescription>
                                        {t('company.dashboard.recent_jobs.subtitle')}
                                    </CardDescription>
                                </div>
                                <Link href="/dashboard/my-jobs">
                                    <Button variant="ghost" size="sm">
                                        {t('company.dashboard.recent_jobs.view_all')}
                                    </Button>
                                </Link>
                            </div>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            {recentJobs.length === 0 ? (
                                <p className="text-muted-foreground text-sm">{t('company.dashboard.recent_jobs.empty')}</p>
                            ) : recentJobs.map((job) => (
                                <div
                                    key={job.id}
                                    className="border rounded-lg p-4 hover:bg-muted/50 transition-colors"
                                >
                                    <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                                        <div className="flex-1 min-w-0">
                                            <h3 className="font-semibold text-base sm:text-lg mb-2 truncate">
                                                {job.title}
                                            </h3>
                                            <div className="flex flex-wrap gap-2 text-sm text-muted-foreground mb-3">
                                                <div className="flex items-center gap-1">
                                                    <MapPin className="h-4 w-4 shrink-0" />
                                                    <span className="truncate">{job.location}</span>
                                                </div>
                                                <Badge
                                                    variant="secondary"
                                                    className="whitespace-nowrap"
                                                >
                                                    {job.type}
                                                </Badge>
                                                <div className="flex items-center gap-1">
                                                    <DollarSign className="h-4 w-4 shrink-0" />
                                                    <span className="whitespace-nowrap">
                                                        {job.salaryMin ? `R$ ${job.salaryMin}` : 'A combinar'}
                                                    </span>
                                                </div>
                                            </div>
                                            <div className="flex flex-wrap gap-4 text-sm">
                                                <span className="flex items-center gap-1">
                                                    <Users className="h-4 w-4" />
                                                    {/* Mocking app count if not available */}
                                                    {t('company.dashboard.recent_jobs.applications_count', { count: job.applicationCount || 0 })}
                                                </span>
                                                <span className="flex items-center gap-1">
                                                    <Calendar className="h-4 w-4" />
                                                    {formatDistanceToNow(new Date(job.createdAt), { addSuffix: true, locale: ptBR })}
                                                </span>
                                            </div>
                                        </div>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="shrink-0"
                                        >
                                            <MoreVertical className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                </div>

                {/* Recent applications */}
                <div>
                    <Card>
                        <CardHeader>
                            <div className="flex items-center justify-between">
                                <div>
                                    <CardTitle>{t('company.dashboard.recent_applications.title')}</CardTitle>
                                    <CardDescription>{t('company.dashboard.recent_applications.subtitle')}</CardDescription>
                                </div>
                                <Link href="/dashboard/candidates">
                                    <Button variant="ghost" size="sm">
                                        {t('company.dashboard.recent_applications.view_all')}
                                    </Button>
                                </Link>
                            </div>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            {recentApplications.length === 0 ? (
                                <p className="text-muted-foreground text-sm">{t('company.dashboard.recent_applications.empty')}</p>
                            ) : recentApplications.map((application) => (
                                <div
                                    key={application.id}
                                    className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors cursor-pointer"
                                >
                                    <div className="relative">
                                        <Avatar className="h-10 w-10">
                                            <AvatarFallback className="bg-primary/10 text-primary text-sm">
                                                {application.name
                                                    .split(" ")
                                                    .map((n: string) => n[0])
                                                    .slice(0, 2)
                                                    .join("")
                                                    .toUpperCase()}
                                            </AvatarFallback>
                                        </Avatar>
                                        <span
                                            className={`absolute -top-1 -right-1 h-3 w-3 rounded-full ${statusColors[
                                                application.status
                                            ] || "bg-gray-400"
                                                } border-2 border-background`}
                                        />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className="font-medium text-sm truncate">
                                            {application.name}
                                        </p>
                                        <p className="text-xs text-muted-foreground truncate">
                                            {application.jobTitle || t('company.dashboard.recent_applications.unknown_job')}
                                        </p>
                                        <p className="text-xs text-muted-foreground mt-1">
                                            {formatDistanceToNow(new Date(application.created_at), { addSuffix: true, locale: ptBR })}
                                        </p>
                                    </div>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    )
}
