
'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,
} from '@/components/ui/form';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
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 { handleShiftSwapRequest } from '@/lib/actions';
import { type Employee } from '@/lib/types';

type Translation = {
    shiftDate: string;
    pickDate: string;
    requestCoverFrom: string;
    selectEmployee: string;
    reason: string;
    placeholder: string;
}
type GlobalTranslation = {
    submit: string;
}

const shiftSwapSchema = z.object({
  shiftDate: z.date({ required_error: "Please select the date of the shift." }),
  toEmployeeId: z.string().min(1, "Please select an employee to cover your shift."),
  reason: z.string().optional(),
});

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

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

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

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 max-w-lg">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
                control={form.control}
                name="shiftDate"
                render={({ field }) => (
                    <FormItem className="flex flex-col">
                    <FormLabel>{t.shiftDate}</FormLabel>
                    <Popover>
                        <PopoverTrigger asChild>
                        <FormControl>
                            <Button
                            variant={'outline'}
                            className={cn(
                                'w-full justify-start text-start font-normal',
                                !field.value && 'text-muted-foreground'
                            )}
                            >
                            <CalendarIcon className="me-2 h-4 w-4" />
                            {field.value ? (
                                format(field.value, 'PPP')
                            ) : (
                                <span>{t.pickDate}</span>
                            )}
                            </Button>
                        </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                        <Calendar
                            mode="single"
                            selected={field.value}
                            onSelect={field.onChange}
                            disabled={(date) => date < new Date(new Date().setHours(0,0,0,0))}
                            initialFocus
                        />
                        </PopoverContent>
                    </Popover>
                    <FormMessage />
                    </FormItem>
                )}
            />
            <FormField
                control={form.control}
                name="toEmployeeId"
                render={({ field }) => (
                    <FormItem>
                        <FormLabel>{t.requestCoverFrom}</FormLabel>
                        <Select onValueChange={field.onChange} defaultValue={field.value}>
                            <FormControl>
                                <SelectTrigger>
                                    <SelectValue placeholder={t.selectEmployee} />
                                </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                                {employees.map(e => <SelectItem key={e.id} value={e.id}>{e.name}</SelectItem>)}
                            </SelectContent>
                        </Select>
                        <FormMessage />
                    </FormItem>
                )}
            />
        </div>
       
        <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>
  );
}
