'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { format } from 'date-fns';
import { CalendarIcon, Loader2 } from 'lucide-react';
import { de } from 'date-fns/locale';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import {
  type Employee,
  type CreateEmployeeDto,
  type UpdateEmployeeDto,
  useCreateEmployee,
  useUpdateEmployee,
} from '@/hooks/hr/use-employees';
import type { ContractType, UserRole } from '@/types';

// Mock departments for selection
// TODO: Replace with API call
const mockDepartments = [
  { id: '1', name: 'IT & Entwicklung' },
  { id: '2', name: 'Personal' },
  { id: '3', name: 'Vertrieb' },
  { id: '4', name: 'Lager & Logistik' },
  { id: '5', name: 'Finanzen' },
];

// Zod schema for form validation
const employeeFormSchema = z.object({
  employeeNumber: z.string().min(1, 'required'),
  firstName: z.string().min(1, 'required').max(100),
  lastName: z.string().min(1, 'required').max(100),
  email: z.string().email('invalidEmail'),
  phone: z.string().optional(),
  position: z.string().min(1, 'required'),
  departmentId: z.string().min(1, 'required'),
  managerId: z.string().optional(),
  contractType: z.enum([
    'full_time',
    'part_time',
    'mini_job',
    'intern',
    'trainee',
    'freelance',
  ] as const),
  hireDate: z.date(),
  weeklyHours: z.number().min(1).max(60),
  vacationDaysTotal: z.number().min(0).max(50).optional(),
  street: z.string().optional(),
  city: z.string().optional(),
  zipCode: z.string().optional(),
  country: z.string().optional(),
  emergencyName: z.string().optional(),
  emergencyPhone: z.string().optional(),
  emergencyRelationship: z.string().optional(),
});

type EmployeeFormValues = z.infer<typeof employeeFormSchema>;

interface EmployeeFormProps {
  /** Existing employee data for editing */
  employee?: Employee;
  /** Current locale */
  locale: string;
  /** Mode: create or edit */
  mode: 'create' | 'edit';
}

/**
 * Employee form for creating or editing employee data
 * Includes personal info, employment details, address, and emergency contact
 */
export function EmployeeForm({ employee, locale, mode }: EmployeeFormProps) {
  const t = useTranslations('hr');
  const tContract = useTranslations('hr.contractType');
  const tValidation = useTranslations('validation');
  const tCommon = useTranslations('common');
  const { toast } = useToast();
  const router = useRouter();

  const [isSubmitting, setIsSubmitting] = useState(false);

  const createEmployee = useCreateEmployee();
  const updateEmployee = useUpdateEmployee();

  // Initialize form with existing data or defaults
  const form = useForm<EmployeeFormValues>({
    resolver: zodResolver(employeeFormSchema),
    defaultValues: {
      employeeNumber: employee?.employeeNumber || '',
      firstName: employee?.firstName || '',
      lastName: employee?.lastName || '',
      email: employee?.email || '',
      phone: employee?.phone || '',
      position: employee?.position || '',
      departmentId: employee?.departmentId || '',
      managerId: employee?.managerId || '',
      contractType: employee?.contractType || 'full_time',
      hireDate: employee?.hireDate ? new Date(employee.hireDate) : new Date(),
      weeklyHours: employee?.weeklyHours || 40,
      vacationDaysTotal: employee?.vacationDaysTotal || 30,
      street: employee?.address?.street || '',
      city: employee?.address?.city || '',
      zipCode: employee?.address?.zipCode || '',
      country: employee?.address?.country || 'Deutschland',
      emergencyName: employee?.emergencyContact?.name || '',
      emergencyPhone: employee?.emergencyContact?.phone || '',
      emergencyRelationship: employee?.emergencyContact?.relationship || '',
    },
  });

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = form;

  const hireDate = watch('hireDate');
  const contractType = watch('contractType');
  const departmentId = watch('departmentId');

  // Handle form submission
  const onSubmit = async (data: EmployeeFormValues) => {
    setIsSubmitting(true);

    try {
      // Build DTO
      const dto: CreateEmployeeDto | UpdateEmployeeDto = {
        employeeNumber: data.employeeNumber,
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        phone: data.phone || undefined,
        position: data.position,
        departmentId: data.departmentId,
        managerId: data.managerId || undefined,
        contractType: data.contractType,
        hireDate: format(data.hireDate, 'yyyy-MM-dd'),
        weeklyHours: data.weeklyHours,
        vacationDaysTotal: data.vacationDaysTotal,
      };

      // Add address if provided
      if (data.street || data.city || data.zipCode) {
        dto.address = {
          street: data.street || '',
          city: data.city || '',
          zipCode: data.zipCode || '',
          country: data.country || 'Deutschland',
        };
      }

      // Add emergency contact if provided
      if (data.emergencyName || data.emergencyPhone) {
        dto.emergencyContact = {
          name: data.emergencyName || '',
          phone: data.emergencyPhone || '',
          relationship: data.emergencyRelationship || '',
        };
      }

      if (mode === 'create') {
        await createEmployee.mutateAsync(dto as CreateEmployeeDto);
        toast({
          title: t('toast.employeeCreated'),
          description: t('toast.employeeCreatedDesc'),
        });
      } else if (employee) {
        await updateEmployee.mutateAsync({
          id: employee.id,
          dto: dto as UpdateEmployeeDto,
        });
        toast({
          title: t('toast.employeeUpdated'),
          description: t('toast.employeeUpdatedDesc'),
        });
      }

      // Navigate back to list
      router.push(`/${locale}/hr/employees`);
    } catch (error) {
      toast({
        title: tCommon('error'),
        description:
          mode === 'create' ? t('toast.errorCreate') : t('toast.errorUpdate'),
        variant: 'destructive',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      {/* Personal Information */}
      <Card>
        <CardHeader>
          <CardTitle>{t('form.personalInfo')}</CardTitle>
          <CardDescription>{t('form.personalInfoDesc')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            {/* Employee Number */}
            <div className="space-y-2">
              <Label htmlFor="employeeNumber">{t('employeeNumber')} *</Label>
              <Input
                id="employeeNumber"
                {...register('employeeNumber')}
                placeholder="EMP-XXX"
              />
              {errors.employeeNumber && (
                <p className="text-sm text-destructive">
                  {tValidation(errors.employeeNumber.message as string)}
                </p>
              )}
            </div>

            {/* First Name */}
            <div className="space-y-2">
              <Label htmlFor="firstName">{t('firstName')} *</Label>
              <Input id="firstName" {...register('firstName')} />
              {errors.firstName && (
                <p className="text-sm text-destructive">
                  {tValidation(errors.firstName.message as string)}
                </p>
              )}
            </div>

            {/* Last Name */}
            <div className="space-y-2">
              <Label htmlFor="lastName">{t('lastName')} *</Label>
              <Input id="lastName" {...register('lastName')} />
              {errors.lastName && (
                <p className="text-sm text-destructive">
                  {tValidation(errors.lastName.message as string)}
                </p>
              )}
            </div>

            {/* Email */}
            <div className="space-y-2">
              <Label htmlFor="email">{t('email')} *</Label>
              <Input id="email" type="email" {...register('email')} />
              {errors.email && (
                <p className="text-sm text-destructive">
                  {tValidation(errors.email.message as string)}
                </p>
              )}
            </div>

            {/* Phone */}
            <div className="space-y-2">
              <Label htmlFor="phone">{t('phone')}</Label>
              <Input id="phone" type="tel" {...register('phone')} />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Employment Details */}
      <Card>
        <CardHeader>
          <CardTitle>{t('form.employmentDetails')}</CardTitle>
          <CardDescription>{t('form.employmentDetailsDesc')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            {/* Position */}
            <div className="space-y-2">
              <Label htmlFor="position">{t('position')} *</Label>
              <Input id="position" {...register('position')} />
              {errors.position && (
                <p className="text-sm text-destructive">
                  {tValidation(errors.position.message as string)}
                </p>
              )}
            </div>

            {/* Department */}
            <div className="space-y-2">
              <Label>{t('department')} *</Label>
              <Select
                value={departmentId}
                onValueChange={(value) => setValue('departmentId', value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder={t('selectDepartment')} />
                </SelectTrigger>
                <SelectContent>
                  {mockDepartments.map((dept) => (
                    <SelectItem key={dept.id} value={dept.id}>
                      {dept.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.departmentId && (
                <p className="text-sm text-destructive">
                  {tValidation(errors.departmentId.message as string)}
                </p>
              )}
            </div>

            {/* Contract Type */}
            <div className="space-y-2">
              <Label>{t('contractType.label')} *</Label>
              <Select
                value={contractType}
                onValueChange={(value) =>
                  setValue('contractType', value as ContractType)
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <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>

            {/* Hire Date */}
            <div className="space-y-2">
              <Label>{t('hireDate')} *</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      'w-full justify-start text-left font-normal',
                      !hireDate && 'text-muted-foreground'
                    )}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {hireDate ? (
                      format(hireDate, 'PPP', {
                        locale: locale === 'de' ? de : undefined,
                      })
                    ) : (
                      <span>{t('selectDate')}</span>
                    )}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    mode="single"
                    selected={hireDate}
                    onSelect={(date) => date && setValue('hireDate', date)}
                    initialFocus
                    locale={locale === 'de' ? de : undefined}
                  />
                </PopoverContent>
              </Popover>
            </div>

            {/* Weekly Hours */}
            <div className="space-y-2">
              <Label htmlFor="weeklyHours">{t('weeklyHours')} *</Label>
              <Input
                id="weeklyHours"
                type="number"
                min={1}
                max={60}
                {...register('weeklyHours', { valueAsNumber: true })}
              />
              {errors.weeklyHours && (
                <p className="text-sm text-destructive">
                  {tValidation('invalidNumber')}
                </p>
              )}
            </div>

            {/* Vacation Days */}
            <div className="space-y-2">
              <Label htmlFor="vacationDaysTotal">{t('vacationDaysTotal')}</Label>
              <Input
                id="vacationDaysTotal"
                type="number"
                min={0}
                max={50}
                {...register('vacationDaysTotal', { valueAsNumber: true })}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Address */}
      <Card>
        <CardHeader>
          <CardTitle>{t('form.address')}</CardTitle>
          <CardDescription>{t('form.addressDesc')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2 md:col-span-2">
              <Label htmlFor="street">{t('street')}</Label>
              <Input id="street" {...register('street')} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="zipCode">{t('zipCode')}</Label>
              <Input id="zipCode" {...register('zipCode')} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="city">{t('city')}</Label>
              <Input id="city" {...register('city')} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="country">{t('country')}</Label>
              <Input id="country" {...register('country')} />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Emergency Contact */}
      <Card>
        <CardHeader>
          <CardTitle>{t('form.emergencyContact')}</CardTitle>
          <CardDescription>{t('form.emergencyContactDesc')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="emergencyName">{t('emergencyName')}</Label>
              <Input id="emergencyName" {...register('emergencyName')} />
            </div>

            <div className="space-y-2">
              <Label htmlFor="emergencyPhone">{t('emergencyPhone')}</Label>
              <Input
                id="emergencyPhone"
                type="tel"
                {...register('emergencyPhone')}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="emergencyRelationship">
                {t('emergencyRelationship')}
              </Label>
              <Input
                id="emergencyRelationship"
                {...register('emergencyRelationship')}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Form Actions */}
      <div className="flex justify-end gap-4">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.back()}
          disabled={isSubmitting}
        >
          {tCommon('cancel')}
        </Button>
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
          {mode === 'create' ? t('createEmployee') : tCommon('save')}
        </Button>
      </div>
    </form>
  );
}
