"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 { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { useTransition } from 'react';
import { Loader2 } from 'lucide-react';
import { handleAdvanceRequest } from '@/lib/actions';
import { format } from 'date-fns';

type Translation = {
  requestDate: string;
  amount: string;
  reason: string;
  placeholder: string;
};
type GlobalTranslation = {
    submit: string;
}

const advanceRequestSchema = z.object({
  amount: z.coerce.number().min(1, 'Amount must be greater than zero.'),
  reason: z.string().optional(),
});

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

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

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

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 max-w-lg">
        <FormItem>
            <FormLabel>{t.requestDate}</FormLabel>
            <FormControl>
                <Input value={format(today, 'PPP')} readOnly disabled />
            </FormControl>
        </FormItem>
        
        <FormField
            control={form.control}
            name="amount"
            render={({ field }) => (
                <FormItem>
                <FormLabel>{t.amount}</FormLabel>
                <FormControl>
                    <Input 
                        type="number" 
                        placeholder="0.00" 
                        {...field} 
                        onFocus={(e) => {
                            if (e.target.value === '0') {
                                e.target.value = '';
                            }
                        }}
                    />
                </FormControl>
                <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>
  );
}

    
