"use client";

import { ArrowUpDown, FileText } from "lucide-react";
import { updateApplicationStatus } from "@/app/actions/applicationActions";
import Link from "next/link";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";

interface Application {
    id: string;
    candidateName: string;
    role: string;
    status: 'pending' | 'reviewing' | 'interview' | 'accepted' | 'rejected' | 'withdrawn' | 'offered';
    appliedAt: string;
    avatar: string;
    yearsOfExperience?: number;
    cvLink?: string;
    email?: string;
}

interface ApplicationsTableProps {
    applications: Application[];
}

export function ApplicationsTable({ applications }: ApplicationsTableProps) {
    return (
        <Card>
            <CardHeader className="flex flex-row items-center justify-between">
                <CardTitle className="text-lg">Applications List</CardTitle>
                <Link href="/dashboard/applications" className="text-sm font-semibold text-primary hover:underline">
                    View All
                </Link>
            </CardHeader>
            <CardContent className="p-0">
                <Table>
                    <TableHeader>
                        <TableRow className="bg-slate-50/30">
                            <TableHead className="pl-6">
                                <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
                                    Name <ArrowUpDown className="h-3 w-3" />
                                </div>
                            </TableHead>
                            <TableHead>
                                <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
                                    Email <ArrowUpDown className="h-3 w-3" />
                                </div>
                            </TableHead>
                            <TableHead>
                                <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
                                    Role <ArrowUpDown className="h-3 w-3" />
                                </div>
                            </TableHead>
                            <TableHead>
                                <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
                                    Date <ArrowUpDown className="h-3 w-3" />
                                </div>
                            </TableHead>
                            <TableHead>
                                <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
                                    Resume <ArrowUpDown className="h-3 w-3" />
                                </div>
                            </TableHead>
                            <TableHead>
                                <div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
                                    Status <ArrowUpDown className="h-3 w-3" />
                                </div>
                            </TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {applications.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={6} className="px-6 py-12 text-center text-sm text-slate-400">
                                    No applications yet
                                </TableCell>
                            </TableRow>
                        ) : (
                            applications.map((app) => (
                                <TableRow key={app.id} className="group hover:bg-slate-50/50 transition-colors">
                                    {/* Name with Avatar */}
                                    <TableCell className="pl-6">
                                        <Link
                                            href={`/dashboard/applications/${app.id}`}
                                            className="flex items-center gap-3"
                                        >
                                            <Avatar className="h-10 w-10">
                                                <AvatarFallback className="bg-gradient-to-br from-primary to-accent text-sm font-bold text-white">
                                                    {app.avatar}
                                                </AvatarFallback>
                                            </Avatar>
                                            <span className="font-semibold text-slate-900 group-hover:text-primary transition-colors">
                                                {app.candidateName}
                                            </span>
                                        </Link>
                                    </TableCell>

                                    {/* Email */}
                                    <TableCell>
                                        <span className="text-sm text-slate-600">
                                            {app.email || '-'}
                                        </span>
                                    </TableCell>

                                    {/* Role */}
                                    <TableCell>
                                        <span className="text-sm font-medium text-slate-700">
                                            {app.role}
                                        </span>
                                    </TableCell>

                                    {/* Date */}
                                    <TableCell>
                                        <span className="text-sm text-slate-600">
                                            {new Date(app.appliedAt).toLocaleDateString('en-US', {
                                                month: 'short',
                                                day: 'numeric',
                                                year: 'numeric'
                                            })}
                                        </span>
                                    </TableCell>

                                    {/* Resume */}
                                    <TableCell>
                                        {app.cvLink ? (
                                            <a
                                                href={app.cvLink}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="inline-flex items-center gap-1.5 text-sm font-medium text-primary hover:underline"
                                            >
                                                <FileText className="h-4 w-4" />
                                                View Resume
                                            </a>
                                        ) : (
                                            <span className="text-sm text-slate-400">-</span>
                                        )}
                                    </TableCell>

                                    {/* Status */}
                                    <TableCell>
                                        <StatusBadge status={app.status} id={app.id} />
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>

                {/* Footer with pagination info */}
                {applications.length > 0 && (
                    <div className="border-t border-slate-100 px-6 py-4">
                        <p className="text-sm text-slate-500">
                            Showing 1 to {Math.min(5, applications.length)} of {applications.length} entries
                        </p>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}

function StatusBadge({ status, id }: { status: string, id: string }) {
    const handleChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newStatus = e.target.value as "pending" | "reviewing" | "interview" | "accepted" | "rejected" | "withdrawn" | "offered";
        await updateApplicationStatus(id, newStatus);
    };

    const statusConfig: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
        pending: { label: "Screening", variant: "outline" },
        reviewing: { label: "Shortlisted", variant: "secondary" },
        interview: { label: "Interviewing", variant: "default" },
        accepted: { label: "Job Offer", variant: "default" },
        rejected: { label: "Rejected", variant: "destructive" },
        withdrawn: { label: "Withdrawn", variant: "outline" },
        offered: { label: "Offered", variant: "default" },
    };

    const config = statusConfig[status] || statusConfig.pending;

    return (
        <div className="relative inline-block">
            <select
                defaultValue={status}
                onChange={handleChange}
                className="appearance-none cursor-pointer rounded-lg border-2 px-3 py-1.5 text-xs font-bold tracking-wide outline-none transition-all hover:shadow-sm focus:ring-2 focus:ring-primary/20 border-slate-200 bg-slate-50 text-slate-700"
            >
                <option value="pending">Screening</option>
                <option value="reviewing">Shortlisted</option>
                <option value="interview">Interviewing</option>
                <option value="accepted">Job Offer</option>
                <option value="rejected">Rejected</option>
                <option value="withdrawn">Withdrawn</option>
                <option value="offered">Offered</option>
            </select>
        </div>
    );
}
