"use client";

import { useEffect, useState } from "react";
import { getSingleJobAnalytics } from "@/app/actions/jobAnalyticsActions";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts";
import { Eye, Users, TrendingUp, AlertCircle } from "lucide-react";

interface JobAnalyticsProps {
    jobId: string;
}

type AnalyticsData = {
    totalViews: number;
    totalApplications: number;
    conversionRate: number;
    timeline: { date: string; views: number }[];
} | null;

export function JobAnalytics({ jobId }: JobAnalyticsProps) {
    const [data, setData] = useState<AnalyticsData>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);

    useEffect(() => {
        let isMounted = true;
        getSingleJobAnalytics(jobId)
            .then(res => {
                if (isMounted) {
                    setData(res);
                    setLoading(false);
                }
            })
            .catch(() => {
                if (isMounted) {
                    setError(true);
                    setLoading(false);
                }
            });

        return () => { isMounted = false; };
    }, [jobId]);

    if (loading) {
        return (
            <div className="flex h-64 items-center justify-center rounded-xl border border-slate-100 bg-white shadow-sm p-8">
                <div className="animate-spin rounded-full border-4 border-slate-200 border-t-primary h-10 w-10"></div>
            </div>
        );
    }

    if (error || !data) {
        return (
            <div className="flex flex-col h-64 items-center justify-center rounded-xl border border-red-100 bg-red-50 text-red-600 shadow-sm p-8 text-center gap-3">
                <AlertCircle className="h-10 w-10 opacity-50" />
                <p className="font-medium">Failed to load analytics data.</p>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="grid gap-6 sm:grid-cols-3">
                <div className="rounded-xl border border-slate-100 bg-white p-6 shadow-sm flex flex-col gap-2">
                    <div className="flex items-center gap-2 text-slate-500 font-medium">
                        <Eye className="h-5 w-5 text-blue-500" />
                        <span>Total Views</span>
                    </div>
                    <div className="text-3xl font-bold text-slate-900">{data.totalViews.toLocaleString()}</div>
                    <p className="text-xs text-slate-400">Past 30 days</p>
                </div>

                <div className="rounded-xl border border-slate-100 bg-white p-6 shadow-sm flex flex-col gap-2">
                    <div className="flex items-center gap-2 text-slate-500 font-medium">
                        <Users className="h-5 w-5 text-purple-500" />
                        <span>Applications</span>
                    </div>
                    <div className="text-3xl font-bold text-slate-900">{data.totalApplications.toLocaleString()}</div>
                    <p className="text-xs text-slate-400">All time</p>
                </div>

                <div className="rounded-xl border border-slate-100 bg-white p-6 shadow-sm flex flex-col gap-2">
                    <div className="flex items-center gap-2 text-slate-500 font-medium">
                        <TrendingUp className="h-5 w-5 text-green-500" />
                        <span>Conversion Rate</span>
                    </div>
                    <div className="text-3xl font-bold text-slate-900">{data.conversionRate}%</div>
                    <p className="text-xs text-slate-400">Views to applications</p>
                </div>
            </div>

            <div className="rounded-xl border border-slate-100 bg-white p-6 shadow-sm">
                <h3 className="mb-6 font-bold text-slate-900">Views Over Time (30 Days)</h3>
                <div className="h-72 w-full">
                    <ResponsiveContainer width="100%" height="100%">
                        <LineChart data={data.timeline} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e2e8f0" />
                            <XAxis
                                dataKey="date"
                                tickFormatter={(val) => {
                                    const date = new Date(val);
                                    return `${date.getDate()} ${date.toLocaleString('default', { month: 'short' })}`;
                                }}
                                tick={{ fontSize: 12, fill: '#64748b' }}
                                axisLine={false}
                                tickLine={false}
                                dy={10}
                            />
                            <YAxis
                                tick={{ fontSize: 12, fill: '#64748b' }}
                                axisLine={false}
                                tickLine={false}
                                dx={-10}
                                allowDecimals={false}
                            />
                            <Tooltip
                                labelFormatter={(label) => new Date(label).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' })}
                                contentStyle={{ borderRadius: '0.5rem', border: '1px solid #e2e8f0', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                            />
                            <Line
                                type="monotone"
                                dataKey="views"
                                stroke="#3b82f6"
                                strokeWidth={3}
                                dot={false}
                                activeDot={{ r: 6, fill: '#3b82f6', stroke: '#fff', strokeWidth: 2 }}
                            />
                        </LineChart>
                    </ResponsiveContainer>
                </div>
            </div>
        </div>
    );
}
