'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from '@/components/ui/form';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { useTransition } from 'react';
import { Loader2, CalendarIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { format } from 'date-fns';
import { DateRange } from 'react-day-picker';
import { handleLeaveRequest } from '@/lib/actions';

type Translation = {
    dates: string;
    pickDate: string;
    datesDescription: string;
    reason: string;
    placeholder: string;
}
type GlobalTranslation = {
    submit: string;
}

const leaveRequestSchema = z.object({
    dateRange: z.object({
        from: z.date({ required_error: "Please select a start date." }),
        to: z.date({ required_error: "Please select an end date." }),
    }),
    reason: z.string().min(10, 'Reason must be at least 10 characters.'),
});


export function LeaveRequestForm({t, tGlobal}: {t: Translation, tGlobal: GlobalTranslation}) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();

  const form = useForm<z.infer<typeof leaveRequestSchema>>({
    resolver: zodResolver(leaveRequestSchema),
    defaultValues: {
      reason: '',
    },
  });

  async function onSubmit(values: z.infer<typeof leaveRequestSchema>) {
    startTransition(async () => {
      const result = await handleLeaveRequest(values);
       if (result?.error) {
        toast({
          title: "Submission Failed",
          description: result.error,
          variant: "destructive",
        });
      } else {
        toast({
            title: 'Request Submitted',
            description: 'Your leave request has been sent for approval.',
        });
        form.reset();
      }
    });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 max-w-lg">
        <FormField
            control={form.control}
            name="dateRange"
            render={({ field }) => (
                <FormItem className="flex flex-col">
                <FormLabel>{t.dates}</FormLabel>
                <Popover>
                    <PopoverTrigger asChild>
                    <FormControl>
                        <Button
                        variant={'outline'}
                        className={cn(
                            'w-[300px] justify-start text-start font-normal',
                            !field.value?.from && 'text-muted-foreground'
                        )}
                        >
                        <CalendarIcon className="me-2 h-4 w-4" />
                        {field.value?.from ? (
                            field.value.to ? (
                            <>
                                {format(field.value.from, 'LLL dd, y')} -{' '}
                                {format(field.value.to, 'LLL dd, y')}
                            </>
                            ) : (
                            format(field.value.from, 'LLL dd, y')
                            )
                        ) : (
                            <span>{t.pickDate}</span>
                        )}
                        </Button>
                    </FormControl>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                        initialFocus
                        mode="range"
                        defaultMonth={field.value?.from}
                        selected={{
                            from: field.value?.from,
                            to: field.value?.to,
                        }}
                        onSelect={(range) => field.onChange(range as DateRange)}
                        numberOfMonths={2}
                        disabled={(date) => date < new Date(new Date().setHours(0,0,0,0))}
                    />
                    </PopoverContent>
                </Popover>
                <FormDescription>
                    {t.datesDescription}
                </FormDescription>
                <FormMessage />
                </FormItem>
            )}
            />
       
        <FormField
          control={form.control}
          name="reason"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t.reason}</FormLabel>
              <FormControl>
                <Textarea
                  placeholder={t.placeholder}
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit" disabled={isPending}>
          {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
          {tGlobal.submit}
        </Button>
      </form>
    </Form>
  );
}

    
