'use client';

import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { employeeDirectoryTargetQueryOptions } from '../api/queries';
import { upsertEmployeeDirectoryTargetMutation } from '../api/mutations';

const targetSchema = z
  .object({
    year: z.number().int().min(2000),
    totalHours: z.number().min(0),
    kHours: z.number().min(0),
    sHours: z.number().min(0),
    aHours: z.number().min(0)
  })
  .refine((value) => Number((value.kHours + value.sHours + value.aHours).toFixed(2)) === Number(value.totalHours.toFixed(2)), {
    message: 'ผลรวม K/S/A ต้องเท่ากับชั่วโมงรวม',
    path: ['totalHours']
  });

type TargetFormValues = z.infer<typeof targetSchema>;

export function EmployeeTargetForm({
  employeeId,
  year
}: {
  employeeId: number;
  year: number;
}) {
  const router = useRouter();
  const { data } = useSuspenseQuery(employeeDirectoryTargetQueryOptions(employeeId, year));
  const target = data.target;

  const mutation = useMutation({
    ...upsertEmployeeDirectoryTargetMutation,
    onSuccess: () => {
      toast.success('บันทึกเป้าหมาย K/S/A เรียบร้อยแล้ว');
      router.push(`/dashboard/employee-directory/${employeeId}`);
      router.refresh();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถบันทึกเป้าหมายได้');
    }
  });

  const form = useAppForm({
    defaultValues: {
      year: target.year,
      totalHours: target.totalHours,
      kHours: target.kHours,
      sHours: target.sHours,
      aHours: target.aHours
    } as TargetFormValues,
    validators: {
      onSubmit: targetSchema
    },
    onSubmit: async ({ value }) => {
      mutation.mutate({
        id: employeeId,
        values: value
      });
    }
  });

  const { FormTextField } = useFormFields<TargetFormValues>();

  return (
    <Card className='mx-auto w-full max-w-3xl'>
      <CardHeader>
        <CardTitle className='text-left text-2xl font-bold'>
          กำหนดเป้าหมาย K / S / A
        </CardTitle>
        <div className='text-muted-foreground text-sm'>
          {target.employeeName} ({target.employeeCode}) ปี {target.year + 543}
        </div>
      </CardHeader>
      <CardContent>
        <form.AppForm>
          <form.Form className='space-y-8'>
            <div className='grid grid-cols-1 gap-6 md:grid-cols-2'>
              <FormTextField name='year' label='ปี' type='number' required />
              <FormTextField name='totalHours' label='ชั่วโมงรวม' type='number' required />
              <FormTextField name='kHours' label='เป้าหมาย K' type='number' required />
              <FormTextField name='sHours' label='เป้าหมาย S' type='number' required />
              <FormTextField name='aHours' label='เป้าหมาย A' type='number' required />
            </div>

            <div className='flex justify-end gap-2'>
              <Button
                type='button'
                variant='outline'
                onClick={() => router.push(`/dashboard/employee-directory/${employeeId}`)}
              >
                ยกเลิก
              </Button>
              <form.SubmitButton>บันทึกเป้าหมาย</form.SubmitButton>
            </div>
          </form.Form>
        </form.AppForm>
      </CardContent>
    </Card>
  );
}
