"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { format } from "date-fns";
import {
    Building2,
    MapPin,
    Calendar,
    Clock,
    CheckCircle2,
    XCircle,
    AlertCircle,
    FileText,
    ExternalLink
} from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { applicationsApi } from "@/lib/api";
import { useNotify } from "@/contexts/notification-context";

interface Application {
    id: string;
    jobId: string;
    jobTitle: string;
    companyName: string;
    companyId: string;
    status: string;
    createdAt: string;
    resumeUrl?: string;
    message?: string;
}

const statusConfig: Record<string, { label: string; color: string; icon: any }> = {
    pending: { label: "Pending", color: "bg-yellow-100 text-yellow-800 border-yellow-200", icon: Clock },
    reviewed: { label: "Viewed", color: "bg-blue-100 text-blue-800 border-blue-200", icon: CheckCircle2 },
    shortlisted: { label: "Shortlisted", color: "bg-purple-100 text-purple-800 border-purple-200", icon: CheckCircle2 },
    hired: { label: "Hired", color: "bg-green-100 text-green-800 border-green-200", icon: CheckCircle2 },
    rejected: { label: "Rejected", color: "bg-red-100 text-red-800 border-red-200", icon: XCircle },
};

export default function MyApplicationsPage() {
    const [applications, setApplications] = useState<Application[]>([]);
    const [loading, setLoading] = useState(true);
    const notify = useNotify();

    useEffect(() => {
        async function fetchApplications() {
            try {
                const data = await applicationsApi.listMine();
                setApplications(data || []);
            } catch (error) {
                console.error("Failed to fetch applications:", error);
                notify.error("Error", "Failed to load your applications.");
            } finally {
                setLoading(false);
            }
        }

        fetchApplications();
    }, [notify]);

    if (loading) {
        return (
            <div className="space-y-4">
                <h1 className="text-3xl font-bold">My Applications</h1>
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    {[1, 2, 3].map((i) => (
                        <Card key={i}>
                            <CardHeader>
                                <Skeleton className="h-6 w-3/4" />
                                <Skeleton className="h-4 w-1/2" />
                            </CardHeader>
                            <CardContent>
                                <Skeleton className="h-20 w-full" />
                            </CardContent>
                        </Card>
                    ))}
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <h1 className="text-3xl font-bold">My Applications</h1>
                    <p className="text-muted-foreground mt-1">
                        Track the status of your job applications.
                    </p>
                </div>
                <Button asChild>
                    <Link href="/jobs">Find more jobs</Link>
                </Button>
            </div>

            {applications.length === 0 ? (
                <Card className="border-dashed">
                    <CardContent className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground">
                        <h3 className="text-lg font-semibold mb-2">No applications yet</h3>
                        <p className="mb-6">You haven't applied to any jobs yet.</p>
                        <Button asChild variant="secondary">
                            <Link href="/jobs">Browse Jobs</Link>
                        </Button>
                    </CardContent>
                </Card>
            ) : (
                <div className="grid gap-4 md:grid-cols-1 lg:grid-cols-2">
                    {applications.map((app) => {
                        const status = statusConfig[app.status] || {
                            label: app.status,
                            color: "bg-gray-100 text-gray-800 border-gray-200",
                            icon: AlertCircle
                        };
                        const StatusIcon = status.icon;

                        return (
                            <Card key={app.id} className="hover:border-primary/50 transition-colors">
                                <CardHeader>
                                    <div className="flex justify-between items-start gap-4">
                                        <div className="space-y-1">
                                            <CardTitle className="text-xl">
                                                <Link href={`/jobs/${app.jobId}`} className="hover:underline hover:text-primary transition-colors">
                                                    {app.jobTitle}
                                                </Link>
                                            </CardTitle>
                                            <div className="flex items-center text-muted-foreground text-sm gap-2">
                                                <Building2 className="h-4 w-4" />
                                                <span>{app.companyName}</span>
                                            </div>
                                        </div>
                                        <Badge variant="outline" className={`${status.color} flex items-center gap-1 shrink-0`}>
                                            <StatusIcon className="h-3 w-3" />
                                            {status.label}
                                        </Badge>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                                        <div className="flex items-center gap-1">
                                            <Calendar className="h-4 w-4" />
                                            Applied on {format(new Date(app.createdAt), "MMM d, yyyy")}
                                        </div>
                                    </div>

                                    {app.message && (
                                        <div className="bg-muted/50 p-3 rounded-md text-sm italic">
                                            "{app.message.length > 100 ? app.message.substring(0, 100) + "..." : app.message}"
                                        </div>
                                    )}

                                    <div className="flex items-center gap-2 pt-2">
                                        {app.resumeUrl && (
                                            <Button variant="outline" size="sm" asChild>
                                                <a href={app.resumeUrl} target="_blank" rel="noopener noreferrer">
                                                    <FileText className="h-4 w-4 mr-2" />
                                                    View Resume
                                                </a>
                                            </Button>
                                        )}
                                        <Button variant="ghost" size="sm" asChild className="ml-auto">
                                            <Link href={`/jobs/${app.jobId}`}>
                                                View Job <ExternalLink className="h-3 w-3 ml-1" />
                                            </Link>
                                        </Button>
                                    </div>
                                </CardContent>
                            </Card>
                        );
                    })}
                </div>
            )}
        </div>
    );
}
