'use client';

import { useState, useMemo } from 'react';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { ColumnDef } from '@tanstack/react-table';
import {
  MoreHorizontal,
  Eye,
  Edit,
  Trash2,
  UserCheck,
  UserX,
} from 'lucide-react';
import { format } from 'date-fns';
import { de } from 'date-fns/locale';

import { DataTable, DataTableColumnHeader } from '@/components/ui/data-table';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import {
  type Employee,
  type EmploymentStatus,
  type QueryEmployeesParams,
  useEmployees,
  useDeleteEmployee,
  EMPLOYMENT_STATUS_COLORS,
} from '@/hooks/hr/use-employees';
import type { ContractType } from '@/types';

interface EmployeeListProps {
  /** Current locale */
  locale: string;
  /** Optional department filter */
  departmentId?: string;
}

/**
 * Employee list with DataTable
 * Features: search, filter by department/status, pagination, actions
 */
export function EmployeeList({ locale, departmentId }: EmployeeListProps) {
  const t = useTranslations('hr');
  const tStatus = useTranslations('hr.employeeStatus');
  const tContract = useTranslations('hr.contractType');
  const tCommon = useTranslations('common');
  const { toast } = useToast();

  // Filter state
  const [statusFilter, setStatusFilter] = useState<EmploymentStatus | 'all'>('all');
  const [contractFilter, setContractFilter] = useState<ContractType | 'all'>('all');

  // Build query params
  const queryParams: QueryEmployeesParams = useMemo(() => {
    const params: QueryEmployeesParams = {
      limit: 50,
    };
    if (departmentId) params.departmentId = departmentId;
    if (statusFilter !== 'all') params.status = statusFilter;
    if (contractFilter !== 'all') params.contractType = contractFilter;
    return params;
  }, [departmentId, statusFilter, contractFilter]);

  // Fetch employees
  const { data, isLoading, error } = useEmployees(queryParams);
  const deleteEmployee = useDeleteEmployee();

  // Handle delete
  const handleDelete = async (id: string, name: string) => {
    if (!confirm(t('confirmDelete', { name }))) return;

    try {
      await deleteEmployee.mutateAsync(id);
      toast({
        title: t('toast.employeeDeleted'),
        description: t('toast.employeeDeletedDesc'),
      });
    } catch (err) {
      toast({
        title: tCommon('error'),
        description: t('toast.errorDelete'),
        variant: 'destructive',
      });
    }
  };

  // Column definitions
  const columns: ColumnDef<Employee>[] = useMemo(
    () => [
      {
        accessorKey: 'name',
        header: ({ column }) => (
          <DataTableColumnHeader column={column} title={t('name')} />
        ),
        cell: ({ row }) => {
          const employee = row.original;
          const initials = `${employee.firstName.charAt(0)}${employee.lastName.charAt(0)}`;
          return (
            <div className="flex items-center gap-3">
              <Avatar className="h-9 w-9">
                <AvatarImage
                  src={employee.avatarUrl}
                  alt={`${employee.firstName} ${employee.lastName}`}
                />
                <AvatarFallback className="bg-primary/10 text-primary text-sm">
                  {initials}
                </AvatarFallback>
              </Avatar>
              <div>
                <div className="font-medium">
                  {employee.firstName} {employee.lastName}
                </div>
                <div className="text-sm text-muted-foreground">
                  {employee.employeeNumber}
                </div>
              </div>
            </div>
          );
        },
        filterFn: (row, id, value) => {
          const employee = row.original;
          const searchValue = value.toLowerCase();
          return (
            employee.firstName.toLowerCase().includes(searchValue) ||
            employee.lastName.toLowerCase().includes(searchValue) ||
            employee.employeeNumber.toLowerCase().includes(searchValue) ||
            employee.email.toLowerCase().includes(searchValue)
          );
        },
      },
      {
        accessorKey: 'position',
        header: ({ column }) => (
          <DataTableColumnHeader column={column} title={t('position')} />
        ),
        cell: ({ row }) => <span>{row.original.position}</span>,
      },
      {
        accessorKey: 'department',
        header: ({ column }) => (
          <DataTableColumnHeader column={column} title={t('department')} />
        ),
        cell: ({ row }) => (
          <span>{row.original.department?.name || '-'}</span>
        ),
      },
      {
        accessorKey: 'contractType',
        header: ({ column }) => (
          <DataTableColumnHeader column={column} title={t('contractType.label')} />
        ),
        cell: ({ row }) => (
          <span>{tContract(row.original.contractType)}</span>
        ),
      },
      {
        accessorKey: 'status',
        header: ({ column }) => (
          <DataTableColumnHeader column={column} title={t('status')} />
        ),
        cell: ({ row }) => {
          const status = row.original.status;
          const colors = EMPLOYMENT_STATUS_COLORS[status];
          return (
            <Badge
              variant="outline"
              className={cn(
                'font-medium border',
                colors.bg,
                colors.text,
                colors.border
              )}
            >
              {tStatus(status)}
            </Badge>
          );
        },
      },
      {
        accessorKey: 'hireDate',
        header: ({ column }) => (
          <DataTableColumnHeader column={column} title={t('hireDate')} />
        ),
        cell: ({ row }) => (
          <span>
            {format(new Date(row.original.hireDate), 'PP', {
              locale: locale === 'de' ? de : undefined,
            })}
          </span>
        ),
      },
      {
        id: 'actions',
        cell: ({ row }) => {
          const employee = row.original;
          return (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                  <span className="sr-only">{tCommon('openMenu')}</span>
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>{tCommon('actions')}</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem asChild>
                  <Link href={`/${locale}/hr/employees/${employee.id}`}>
                    <Eye className="mr-2 h-4 w-4" />
                    {t('viewDetails')}
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuItem asChild>
                  <Link href={`/${locale}/hr/employees/${employee.id}?edit=true`}>
                    <Edit className="mr-2 h-4 w-4" />
                    {tCommon('edit')}
                  </Link>
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                {employee.status === 'active' ? (
                  <DropdownMenuItem
                    onClick={() =>
                      handleDelete(
                        employee.id,
                        `${employee.firstName} ${employee.lastName}`
                      )
                    }
                    className="text-destructive focus:text-destructive"
                  >
                    <UserX className="mr-2 h-4 w-4" />
                    {t('terminate')}
                  </DropdownMenuItem>
                ) : (
                  <DropdownMenuItem className="text-green-600 focus:text-green-600">
                    <UserCheck className="mr-2 h-4 w-4" />
                    {t('reactivate')}
                  </DropdownMenuItem>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          );
        },
      },
    ],
    [locale, t, tStatus, tContract, tCommon, handleDelete]
  );

  // Loading state
  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex gap-4">
          <Skeleton className="h-10 w-[180px]" />
          <Skeleton className="h-10 w-[180px]" />
        </div>
        <Skeleton className="h-[400px] w-full" />
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-12">
        <p className="text-destructive">{tCommon('error')}</p>
        <p className="text-sm text-muted-foreground">
          {error instanceof Error ? error.message : 'Unknown error'}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-wrap gap-4">
        {/* Status Filter */}
        <Select
          value={statusFilter}
          onValueChange={(value) => setStatusFilter(value as EmploymentStatus | 'all')}
        >
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder={t('filterByStatus')} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{tCommon('all')}</SelectItem>
            <SelectItem value="active">{tStatus('active')}</SelectItem>
            <SelectItem value="on_leave">{tStatus('on_leave')}</SelectItem>
            <SelectItem value="inactive">{tStatus('inactive')}</SelectItem>
            <SelectItem value="terminated">{tStatus('terminated')}</SelectItem>
          </SelectContent>
        </Select>

        {/* Contract Type Filter */}
        <Select
          value={contractFilter}
          onValueChange={(value) => setContractFilter(value as ContractType | 'all')}
        >
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder={t('filterByContract')} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{tCommon('all')}</SelectItem>
            <SelectItem value="full_time">{tContract('full_time')}</SelectItem>
            <SelectItem value="part_time">{tContract('part_time')}</SelectItem>
            <SelectItem value="mini_job">{tContract('mini_job')}</SelectItem>
            <SelectItem value="trainee">{tContract('trainee')}</SelectItem>
            <SelectItem value="intern">{tContract('intern')}</SelectItem>
            <SelectItem value="freelance">{tContract('freelance')}</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Data Table */}
      <DataTable
        columns={columns}
        data={data?.data || []}
        searchColumn="name"
        searchPlaceholder={t('searchEmployees')}
        showPagination
      />
    </div>
  );
}
