"use client"

import { StatsCard } from "@/components/stats-card"
import { JobCard } from "@/components/job-card"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table"
import { mockNotifications } from "@/lib/mock-data"
import { jobsApi, applicationsApi, transformApiJobToFrontend } from "@/lib/api"
import { Job, ApplicationWithDetails } from "@/lib/types"
import {
    Bell,
    FileText,
    Clock,
    CheckCircle,
    XCircle,
    AlertCircle,
    Edit,
} from "lucide-react"
import { motion } from "framer-motion"
import { getCurrentUser } from "@/lib/auth"
import { useTranslation } from "@/lib/i18n"
import { useState, useEffect } from "react"

export function CandidateDashboardContent() {
    const { t } = useTranslation()
    const user = getCurrentUser()
    const [jobs, setJobs] = useState<Job[]>([])
    const [applications, setApplications] = useState<ApplicationWithDetails[]>([])
    const [loading, setLoading] = useState(true)

    const unreadNotifications = mockNotifications.filter((n) => !n.read)

    useEffect(() => {
        async function fetchData() {
            try {
                // Fetch recommended jobs (latest ones for now)
                const jobsRes = await jobsApi.list({ limit: 3, sortBy: "created_at" });
                const appsRes = await applicationsApi.listMine();

                if (jobsRes && jobsRes.data) {
                    const mappedJobs = jobsRes.data.map(transformApiJobToFrontend);
                    setJobs(mappedJobs);
                }

                if (appsRes) {
                    setApplications(appsRes);
                }

            } catch (error) {
                console.error("Failed to fetch dashboard data", error);
            } finally {
                setLoading(false);
            }
        }
        fetchData();
    }, []);

    const recommendedJobs = jobs

    const getStatusBadge = (status: string) => {
        switch (status) {
            case "pending":
                return (
                    <Badge variant="secondary">
                        <Clock className="h-3 w-3 mr-1" />
                        {t('candidate.dashboard.status.under_review')}
                    </Badge>
                )
            case "reviewing":
                return (
                    <Badge variant="secondary">
                        <AlertCircle className="h-3 w-3 mr-1" />
                        {t('candidate.dashboard.status.under_review')}
                    </Badge>
                )
            case "interview":
                return (
                    <Badge className="bg-blue-500 hover:bg-blue-600">
                        <CheckCircle className="h-3 w-3 mr-1" />
                        {t('candidate.dashboard.status.interview')}
                    </Badge>
                )
            case "accepted":
                return (
                    <Badge className="bg-green-500 hover:bg-green-600">
                        <CheckCircle className="h-3 w-3 mr-1" />
                        {t('candidate.dashboard.status.accepted')}
                    </Badge>
                )
            case "rejected":
                return (
                    <Badge variant="destructive">
                        <XCircle className="h-3 w-3 mr-1" />
                        {t('candidate.dashboard.status.rejected')}
                    </Badge>
                )
            default:
                return <Badge variant="outline">{status}</Badge>
        }
    }

    return (
        <div className="space-y-8">
            {/* Profile Summary */}
            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
            >
                <Card className="mb-8">
                    <CardContent className="pt-6">
                        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
                            <div className="flex-1">
                                <h1 className="text-2xl font-bold mb-2">{t('candidate.dashboard.welcome', { name: user?.name || "Candidate" })}</h1>
                                <p className="text-muted-foreground">{user?.area || "Engineering"}</p>
                            </div>
                            <Button className="cursor-pointer">
                                <Edit className="mr-2 h-4 w-4" />
                                {t('candidate.dashboard.edit_profile')}
                            </Button>
                        </div>
                    </CardContent>
                </Card>
            </motion.div>

            {/* Stats */}
            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: 0.1 }}
                className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8"
            >
                <StatsCard
                    title={t('candidate.dashboard.stats.applications')}
                    value={applications.length}
                    icon={FileText}
                    description={t('candidate.dashboard.stats.applications_desc')}
                />
                <StatsCard
                    title={t('candidate.dashboard.stats.in_progress')}
                    value={
                        applications.filter(
                            (a) => ["reviewing", "interview", "pending"].includes(a.status)
                        ).length
                    }
                    icon={Clock}
                    description={t('candidate.dashboard.stats.in_progress_desc')}
                />
                <StatsCard
                    title={t('candidate.dashboard.stats.notifications')}
                    value={unreadNotifications.length}
                    icon={Bell}
                    description={t('candidate.dashboard.stats.notifications_desc')}
                />
            </motion.div>

            <div className="grid grid-cols-1 lg:grid-cols-1 gap-8">
                {/* Main Content */}
                <div className="space-y-8">
                    {/* Recommended Jobs */}
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.5, delay: 0.2 }}
                    >
                        <Card>
                            <CardHeader>
                                <CardTitle>{t('candidate.dashboard.recommended.title')}</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {loading ? (
                                    <div className="text-center py-4">Loading jobs...</div>
                                ) : jobs.length > 0 ? (
                                    recommendedJobs.map((job) => {
                                        // Check if applied
                                        const isApplied = applications.some(app => app.jobId === job.id);
                                        return (
                                            <JobCard
                                                key={job.id}
                                                job={job}
                                                isApplied={isApplied}
                                                applicationStatus={isApplied ? applications.find(app => app.jobId === job.id)?.status : undefined}
                                            />
                                        );
                                    })
                                ) : (
                                    <div className="text-center py-4 text-muted-foreground">
                                        No recommended jobs found at this time.
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </motion.div>

                    {/* Applications */}
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.5, delay: 0.3 }}
                    >
                        <Card>
                            <CardHeader>
                                <CardTitle>{t('candidate.dashboard.applications.title')}</CardTitle>
                            </CardHeader>
                            <CardContent>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>{t('candidate.dashboard.applications.table.role')}</TableHead>
                                            <TableHead>{t('candidate.dashboard.applications.table.company')}</TableHead>
                                            <TableHead>{t('candidate.dashboard.applications.table.status')}</TableHead>
                                            <TableHead>{t('candidate.dashboard.applications.table.date')}</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {applications.length > 0 ? applications.map((application) => (
                                            <TableRow key={application.id}>
                                                <TableCell className="font-medium">
                                                    {application.job?.title || "Unknown Job"}
                                                </TableCell>
                                                <TableCell>{application.job?.companyName || "Unknown Company"}</TableCell>
                                                <TableCell>
                                                    {getStatusBadge(application.status)}
                                                </TableCell>
                                                <TableCell className="text-muted-foreground">
                                                    {new Date(application.createdAt).toLocaleDateString(
                                                        "pt-BR"
                                                    )}
                                                </TableCell>
                                            </TableRow>
                                        )) : (
                                            <TableRow>
                                                <TableCell colSpan={4} className="text-center text-muted-foreground py-4">
                                                    {t('candidate.dashboard.applications.empty')}
                                                </TableCell>
                                            </TableRow>
                                        )}
                                    </TableBody>
                                </Table>
                            </CardContent>
                        </Card>
                    </motion.div>
                </div>
            </div>
        </div>
    )
}
