'use client';

import { useMutation } 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 { createEmployeeMutation, updateEmployeeMutation } from '../api/mutations';
import type { Employee } from '../api/types';
import { employeeSchema, type EmployeeFormValues } from '../schemas/employee';

const createSuccessMessage =
  '\u0e2a\u0e23\u0e49\u0e32\u0e07\u0e02\u0e49\u0e2d\u0e21\u0e39\u0e25\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e40\u0e23\u0e35\u0e22\u0e1a\u0e23\u0e49\u0e2d\u0e22\u0e41\u0e25\u0e49\u0e27';
const updateSuccessMessage =
  '\u0e2d\u0e31\u0e1b\u0e40\u0e14\u0e15\u0e02\u0e49\u0e2d\u0e21\u0e39\u0e25\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e40\u0e23\u0e35\u0e22\u0e1a\u0e23\u0e49\u0e2d\u0e22\u0e41\u0e25\u0e49\u0e27';
const employeeCodeLabel = '\u0e23\u0e2b\u0e31\u0e2a\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19';
const employeeCodeError =
  '\u0e01\u0e23\u0e38\u0e13\u0e32\u0e01\u0e23\u0e2d\u0e01\u0e23\u0e2b\u0e31\u0e2a\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e2d\u0e22\u0e48\u0e32\u0e07\u0e19\u0e49\u0e2d\u0e22 2 \u0e15\u0e31\u0e27\u0e2d\u0e31\u0e01\u0e29\u0e23';
const fullNameLabel = '\u0e0a\u0e37\u0e48\u0e2d\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19';
const fullNamePlaceholder = '\u0e01\u0e23\u0e2d\u0e01\u0e0a\u0e37\u0e48\u0e2d\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19';
const fullNameError =
  '\u0e01\u0e23\u0e38\u0e13\u0e32\u0e01\u0e23\u0e2d\u0e01\u0e0a\u0e37\u0e48\u0e2d\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e2d\u0e22\u0e48\u0e32\u0e07\u0e19\u0e49\u0e2d\u0e22 2 \u0e15\u0e31\u0e27\u0e2d\u0e31\u0e01\u0e29\u0e23';
const emailLabel = '\u0e2d\u0e35\u0e40\u0e21\u0e25';
const companyLabel = '\u0e1a\u0e23\u0e34\u0e29\u0e31\u0e17';
const departmentLabel = '\u0e1d\u0e48\u0e32\u0e22';
const departmentPlaceholder = '\u0e01\u0e23\u0e2d\u0e01\u0e0a\u0e37\u0e48\u0e2d\u0e1d\u0e48\u0e32\u0e22';
const positionLabel = '\u0e15\u0e33\u0e41\u0e2b\u0e19\u0e48\u0e07';
const positionPlaceholder = '\u0e01\u0e23\u0e2d\u0e01\u0e0a\u0e37\u0e48\u0e2d\u0e15\u0e33\u0e41\u0e2b\u0e19\u0e48\u0e07';
const activeLabel = '\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e43\u0e0a\u0e49\u0e07\u0e32\u0e19\u0e2d\u0e22\u0e39\u0e48';
const activeDescription =
  '\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e17\u0e35\u0e48\u0e1b\u0e34\u0e14\u0e43\u0e0a\u0e49\u0e07\u0e32\u0e19\u0e08\u0e30\u0e22\u0e31\u0e07\u0e2d\u0e22\u0e39\u0e48\u0e43\u0e19\u0e1b\u0e23\u0e30\u0e27\u0e31\u0e15\u0e34 \u0e41\u0e15\u0e48\u0e08\u0e30\u0e44\u0e21\u0e48\u0e41\u0e2a\u0e14\u0e07\u0e43\u0e19\u0e23\u0e32\u0e22\u0e0a\u0e37\u0e48\u0e2d\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19\u0e17\u0e35\u0e48\u0e43\u0e0a\u0e49\u0e07\u0e32\u0e19';
const cancelLabel = '\u0e22\u0e01\u0e40\u0e25\u0e34\u0e01';
const saveEditLabel = '\u0e1a\u0e31\u0e19\u0e17\u0e36\u0e01\u0e01\u0e32\u0e23\u0e41\u0e01\u0e49\u0e44\u0e02';
const createLabel = '\u0e2a\u0e23\u0e49\u0e32\u0e07\u0e1e\u0e19\u0e31\u0e01\u0e07\u0e32\u0e19';

export default function EmployeeForm({
  initialData,
  pageTitle,
  organizationName,
  returnPath = '/dashboard/employee-directory'
}: {
  initialData: Employee | null;
  pageTitle: string;
  organizationName: string;
  returnPath?: string;
}) {
  const router = useRouter();
  const isEdit = !!initialData;

  const createMutation = useMutation({
    ...createEmployeeMutation,
    onSuccess: () => {
      toast.success(createSuccessMessage);
      router.push(returnPath);
    },
    onError: (error) => {
      toast.error(error.message);
    }
  });

  const updateMutation = useMutation({
    ...updateEmployeeMutation,
    onSuccess: () => {
      toast.success(updateSuccessMessage);
      router.push(returnPath);
    },
    onError: (error) => {
      toast.error(error.message);
    }
  });

  const form = useAppForm({
    defaultValues: {
      employeeCode: initialData?.employee_code ?? '',
      fullName: initialData?.full_name ?? '',
      email: initialData?.email ?? '',
      departmentName: initialData?.department_name ?? '',
      positionName: initialData?.position_name ?? '',
      isActive: initialData?.is_active ?? true
    } as EmployeeFormValues,
    validators: {
      onSubmit: employeeSchema
    },
    onSubmit: async ({ value }) => {
      const payload = {
        employeeCode: value.employeeCode,
        fullName: value.fullName,
        email: value.email,
        departmentName: value.departmentName,
        positionName: value.positionName,
        isActive: value.isActive
      };

      if (isEdit && initialData) {
        updateMutation.mutate({ id: initialData.id, values: payload });
      } else {
        createMutation.mutate(payload);
      }
    }
  });

  const { FormTextField, FormSwitchField } = useFormFields<EmployeeFormValues>();

  return (
    <Card className='mx-auto w-full'>
      <CardHeader>
        <CardTitle className='text-left text-2xl font-bold'>{pageTitle}</CardTitle>
      </CardHeader>
      <CardContent>
        <form.AppForm>
          <form.Form className='space-y-8'>
            <div className='grid grid-cols-1 gap-6 md:grid-cols-2'>
              <FormTextField
                name='employeeCode'
                label={employeeCodeLabel}
                required
                placeholder='EMP-001'
                validators={{
                  onBlur: z.string().min(2, employeeCodeError)
                }}
              />

              <FormTextField
                name='fullName'
                label={fullNameLabel}
                required
                placeholder={fullNamePlaceholder}
                validators={{
                  onBlur: z.string().min(2, fullNameError)
                }}
              />

              <FormTextField
                name='email'
                label={emailLabel}
                type='email'
                placeholder='employee@company.com'
                validators={{
                  onBlur: z.string().optional()
                }}
              />

              <div className='space-y-2'>
                <div className='text-sm font-medium'>{companyLabel}</div>
                <div className='bg-muted/40 text-foreground flex min-h-10 items-center rounded-md border px-3 py-2 text-sm'>
                  {organizationName}
                </div>
              </div>

              <FormTextField
                name='departmentName'
                label={departmentLabel}
                placeholder={departmentPlaceholder}
              />

              <FormTextField
                name='positionName'
                label={positionLabel}
                placeholder={positionPlaceholder}
              />
            </div>

            <FormSwitchField
              name='isActive'
              label={activeLabel}
              description={activeDescription}
            />

            <div className='flex justify-end gap-2'>
              <Button type='button' variant='outline' onClick={() => router.push(returnPath)}>
                {cancelLabel}
              </Button>
              <form.SubmitButton>{isEdit ? saveEditLabel : createLabel}</form.SubmitButton>
            </div>
          </form.Form>
        </form.AppForm>
      </CardContent>
    </Card>
  );
}
