'use client';

import type { User } from '@/types';
import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { toast } from 'react-toastify';
import type { ColumnDef } from '@tanstack/react-table';
import { api } from '@/lib/api';
import ProfileCompletionModal from '@/components/careers/ProfileCompletionModal';
import { DataTable } from '@/components/data-table/DataTable';

interface MyApp {
  application_id: number;
  job_id: number;
  job_public_id?: string;
  job_title: string | null;
  location: string | null;
  stage: string | null;
  round1_outcome: string;
  applied_at: string;
}

const STAGE_COLOR: Record<string, string> = {
  Contacted: 'bg-blue-100 text-blue-700 dark:bg-blue-950/40 dark:text-blue-300',
  Shortlisted: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-300',
  Interview: 'bg-purple-100 text-purple-700 dark:bg-purple-950/40 dark:text-purple-300',
  Selected: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300',
  Offer: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300',
  Rejected: 'bg-rose-100 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300',
};

// Reusable DataTable columns for the candidate's applications list
const APP_COLUMNS: ColumnDef<MyApp>[] = [
  {
    accessorKey: 'job_title',
    header: 'Role',
    cell: ({ row }) => (
      <Link href={`/careers/jobs/${row.original.job_public_id || row.original.job_id}`} className="font-semibold text-slate-800 dark:text-slate-200 hover:text-[#405189]">
        {row.original.job_title || `Job #${row.original.job_id}`}
      </Link>
    ),
  },
  { accessorKey: 'location', header: 'Location', cell: ({ getValue }) => (getValue() as string) || '—' },
  {
    accessorKey: 'applied_at',
    header: 'Applied On',
    cell: ({ getValue }) => (
      <span className="whitespace-nowrap">
        {new Date(getValue() as string).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })}
      </span>
    ),
  },
  {
    accessorKey: 'stage',
    header: 'Stage',
    cell: ({ getValue }) => {
      const stage = (getValue() as string) || '';
      return (
        <span className={`px-2 py-0.5 rounded-none text-[10px] font-bold ${STAGE_COLOR[stage] || 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'}`}>
          {stage || 'Applied'}
        </span>
      );
    },
  },
];

export default function CandidateDashboard({ user }: { user: User }) {
  const name = user.full_name || user.email.split('@')[0];
  const [apps, setApps] = useState<MyApp[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/public/my-applications/')
      .then((res: any) => setApps(res?.data ?? []))
      .catch((e: unknown) => {
        setApps([]);
        toast.error(e instanceof Error ? e.message : 'Could not load your applications. Please refresh.');
      })
      .finally(() => setLoading(false));
  }, []);

  const stats = [
    { title: 'Applied Jobs', value: apps.length, icon: 'fa-solid fa-paper-plane', color: 'bg-teal-500' },
    { title: 'In Progress', value: apps.filter((a) => !['Selected', 'Rejected', 'Offer'].includes(a.stage || '')).length, icon: 'fa-solid fa-hourglass-half', color: 'bg-amber-500' },
    { title: 'Selected', value: apps.filter((a) => ['Selected', 'Offer'].includes(a.stage || '')).length, icon: 'fa-solid fa-circle-check', color: 'bg-emerald-500' },
    { title: 'Not Selected', value: apps.filter((a) => a.stage === 'Rejected').length, icon: 'fa-solid fa-circle-xmark', color: 'bg-rose-500' },
  ];

  return (
    <div className="space-y-5">
      <ProfileCompletionModal />
      {/* Banner */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="rounded-none p-6 text-white relative overflow-hidden"
        style={{ background: 'linear-gradient(135deg,#23b7e5 0%,#405189 100%)' }}
      >
        <div className="relative z-10 flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-sm font-medium opacity-75">Candidate Portal</p>
            <h1 className="text-2xl font-bold mt-0.5">{name} 👋</h1>
            <p className="text-sm opacity-60 mt-1">{new Date().toLocaleDateString('en-IN', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })}</p>
          </div>
          <div className="flex gap-2">
            <Link href="/careers/profile" className="px-5 py-2.5 border border-white/60 text-white font-bold text-sm hover:bg-white/10 transition">
              Edit profile
            </Link>
            <Link href="/careers/jobs" className="px-5 py-2.5 bg-white text-[#405189] font-bold text-sm hover:bg-slate-100 transition">
              Browse jobs
            </Link>
          </div>
        </div>
        <div className="absolute -right-10 -top-10 w-36 h-36 rounded-full bg-white/10 pointer-events-none" />
      </motion.div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {stats.map((card, i) => (
          <motion.div
            key={card.title}
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.07 }}
            className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm"
          >
            <div className={`w-11 h-11 rounded-none ${card.color} flex items-center justify-center mb-3`}>
              <i className={`${card.icon} text-white text-base`} />
            </div>
            <p className="text-[11px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">{card.title}</p>
            <p className="text-2xl font-bold text-slate-900 dark:text-white mt-0.5">{card.value}</p>
          </motion.div>
        ))}
      </div>

      {/* Applied Jobs — reusable DataTable */}
      <div className="space-y-2">
        <h3 className="text-sm font-bold text-slate-800 dark:text-white">My Applications</h3>
        {!loading && apps.length === 0 ? (
          <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-5 shadow-sm py-10 text-center">
            <p className="text-slate-500 dark:text-slate-400 text-sm">You haven&apos;t applied to any jobs yet.</p>
            <Link href="/careers/jobs" className="inline-block mt-3 px-5 py-2 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition">
              Find jobs to apply
            </Link>
          </div>
        ) : (
          <DataTable
            columns={APP_COLUMNS}
            data={apps}
            loading={loading}
            compact
            searchPlaceholder="Search applications…"
            emptyStateTitle="No applications"
            emptyStateDescription="Jobs you apply to will appear here."
          />
        )}
      </div>
    </div>
  );
}
