
"use client";

import { useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { format } from "date-fns";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { handleSwapShifts } from "@/lib/actions";
import { type Employee } from "@/lib/types";
import { Loader2 } from "lucide-react";

const swapShiftsSchema = z.object({
  date: z.string(),
  employee1Id: z.string().min(1, "First employee is required"),
  employee2Id: z.string().min(1, "Second employee is required"),
});

type Translation = {
    swapTitle: string;
    swapDescription: string;
    employee1: string;
    employee2: string;
    confirmSwap: string;
    noEmployees: string;
}

interface SwapShiftDialogProps {
  isOpen: boolean;
  onClose: () => void;
  date: Date;
  employees: Employee[];
  t: Translation;
}

export function SwapShiftDialog({ isOpen, onClose, date, employees, t }: SwapShiftDialogProps) {
    const [isPending, startTransition] = useTransition();
    const { toast } = useToast();

    const form = useForm<z.infer<typeof swapShiftsSchema>>({
        resolver: zodResolver(swapShiftsSchema),
        defaultValues: {
            date: date.toISOString(),
            employee1Id: "",
            employee2Id: "",
        },
    });

    async function onSubmit(values: z.infer<typeof swapShiftsSchema>) {
        startTransition(async () => {
            const result = await handleSwapShifts(values);
            if (result.success) {
                toast({ title: 'تم تبديل الورديات', description: result.message });
                onClose();
            } else {
                toast({ title: 'خطأ', description: result.error, variant: 'destructive' });
            }
        });
    }

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>{t.swapTitle}</DialogTitle>
                    <DialogDescription>
                        {t.swapDescription.replace('{date}', format(date, 'PPP'))}
                    </DialogDescription>
                </DialogHeader>
                 <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 pt-4">
                        <FormField
                            control={form.control}
                            name="employee1Id"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t.employee1}</FormLabel>
                                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder={t.noEmployees} />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            {employees.map(e => <SelectItem key={e.id} value={e.id}>{e.name}</SelectItem>)}
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="employee2Id"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>{t.employee2}</FormLabel>
                                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder={t.noEmployees} />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            {employees.map(e => <SelectItem key={e.id} value={e.id}>{e.name}</SelectItem>)}
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <DialogFooter>
                            <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
                             <Button type="submit" disabled={isPending}>
                                {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                {t.confirmSwap}
                            </Button>
                        </DialogFooter>
                    </form>
                 </Form>
            </DialogContent>
        </Dialog>
    );
}
