'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import {
  Palmtree,
  Calendar,
  Plus,
  ClipboardCheck,
  AlertCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { PageTransition } from '@/components/layout/page-transition';
import {
  VacationBalance,
  AbsenceCard,
  AbsenceRequestForm,
} from '@/components/hr/absences';
import { useMyAbsenceRequests, useCancelAbsence } from '@/hooks/hr/use-absences';
import { useToast } from '@/hooks/use-toast';

interface AbsencesContentProps {
  locale: string;
}

/**
 * Absences overview page content - Client Component
 * Shows vacation balance and personal absence requests
 */
export function AbsencesContent({ locale }: AbsencesContentProps) {
  const t = useTranslations('hr.absences');
  const tCommon = useTranslations('common');
  const { data: session } = useSession();
  const { toast } = useToast();

  const [requestDialog, setRequestDialog] = useState(false);

  const employeeId = session?.user?.id || '1';
  const userRoles = session?.user?.roles || [];
  const canApprove =
    userRoles.includes('manager') ||
    userRoles.includes('department_head') ||
    userRoles.includes('admin');

  const { data: requests, isLoading, error } = useMyAbsenceRequests();
  const cancelAbsence = useCancelAbsence();

  const handleCancel = async (id: string) => {
    try {
      await cancelAbsence.mutateAsync(id);
      toast({
        title: t('cancelled'),
        description: t('cancelledDesc'),
      });
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorCancel'),
        variant: 'destructive',
      });
    }
  };

  return (
    <PageTransition>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{t('title')}</h1>
            <p className="text-muted-foreground">{t('description')}</p>
          </div>
          <div className="flex gap-2">
            <Button asChild variant="outline">
              <Link href={`/${locale}/hr/absences/calendar`} className="gap-2">
                <Calendar className="h-4 w-4" />
                {t('teamCalendar')}
              </Link>
            </Button>
            {canApprove && (
              <Button asChild variant="outline">
                <Link href={`/${locale}/hr/absences/requests`} className="gap-2">
                  <ClipboardCheck className="h-4 w-4" />
                  {t('approvals')}
                </Link>
              </Button>
            )}
            <Button onClick={() => setRequestDialog(true)} className="gap-2">
              <Plus className="h-4 w-4" />
              {t('newRequest')}
            </Button>
          </div>
        </div>

        {/* Main content */}
        <div className="grid gap-6 lg:grid-cols-3">
          {/* Left column: Vacation Balance */}
          <div className="lg:col-span-1">
            <VacationBalance locale={locale} employeeId={employeeId} />
          </div>

          {/* Right column: My Requests */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Palmtree className="h-5 w-5" />
                  {t('myRequests')}
                </CardTitle>
                <CardDescription>{t('myRequestsDesc')}</CardDescription>
              </CardHeader>
              <CardContent>
                {isLoading ? (
                  <div className="space-y-3">
                    {[1, 2, 3].map((i) => (
                      <Skeleton key={i} className="h-24 w-full" />
                    ))}
                  </div>
                ) : error ? (
                  <div className="flex flex-col items-center justify-center py-8">
                    <AlertCircle className="h-10 w-10 text-destructive" />
                    <p className="mt-4 text-muted-foreground">{t('errorLoadingRequests')}</p>
                  </div>
                ) : !requests || requests.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-8 text-center">
                    <Palmtree className="h-10 w-10 text-muted-foreground/50" />
                    <p className="mt-4 text-muted-foreground">{t('noRequests')}</p>
                    <Button
                      variant="outline"
                      className="mt-4 gap-2"
                      onClick={() => setRequestDialog(true)}
                    >
                      <Plus className="h-4 w-4" />
                      {t('createFirstRequest')}
                    </Button>
                  </div>
                ) : (
                  <ScrollArea className="h-[500px] pr-4">
                    <div className="space-y-3">
                      {requests.map((request) => (
                        <AbsenceCard
                          key={request.id}
                          absence={request}
                          locale={locale}
                          onCancel={handleCancel}
                        />
                      ))}
                    </div>
                  </ScrollArea>
                )}
              </CardContent>
            </Card>
          </div>
        </div>

        {/* Request dialog */}
        <AbsenceRequestForm
          open={requestDialog}
          onOpenChange={setRequestDialog}
          locale={locale}
        />
      </div>
    </PageTransition>
  );
}
