'use client';

import { useEffect } from 'react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle
} from '@/components/ui/sheet';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { crmReferenceQueryOptions } from '../api/queries';
import { createCustomerMutation, updateCustomerMutation } from '../api/mutations';
import type { Customer } from '../api/types';
import { customerStatusOptions } from '../data/options';
import { customerSchema, type CustomerFormValues } from '../schemas/customer';

const customerTypeOptions = [
  { value: 'developer', label: 'Developer' },
  { value: 'contractor', label: 'Contractor' },
  { value: 'owner', label: 'Owner' },
  { value: 'consultant', label: 'Consultant' }
];

export function CustomerFormSheet({
  open,
  onOpenChange,
  customer
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  customer?: Customer;
}) {
  const { data: reference } = useSuspenseQuery(crmReferenceQueryOptions());
  const { FormTextField, FormSelectField } = useFormFields<CustomerFormValues>();
  const isEdit = !!customer;
  const baseCreateMutation = createCustomerMutation;
  const baseUpdateMutation = updateCustomerMutation;

  const createMutation = useMutation({
    ...baseCreateMutation,
    onSuccess: async (...args) => {
      await baseCreateMutation.onSuccess?.(...args);
      toast.success('สร้าง customer mock สำเร็จ');
      onOpenChange(false);
    },
    onError: (error) => toast.error(error instanceof Error ? error.message : 'บันทึกไม่สำเร็จ')
  });

  const updateMutation = useMutation({
    ...baseUpdateMutation,
    onSuccess: async (...args) => {
      await baseUpdateMutation.onSuccess?.(...args);
      toast.success('อัปเดต customer mock สำเร็จ');
      onOpenChange(false);
    },
    onError: (error) => toast.error(error instanceof Error ? error.message : 'บันทึกไม่สำเร็จ')
  });

  const form = useAppForm({
    defaultValues: {
      code: customer?.code ?? '',
      name: customer?.name ?? '',
      taxId: customer?.taxId ?? '',
      email: customer?.email ?? '',
      phone: customer?.phone ?? '',
      customerType: customer?.customerType ?? 'developer',
      customerStatus: customer?.customerStatus ?? 'active',
      branchId: customer?.branchId ?? reference.branches[0]?.id ?? '',
      address: customer?.address ?? '',
      province: customer?.province ?? '',
      district: customer?.district ?? '',
      subDistrict: customer?.subDistrict ?? '',
      postalCode: customer?.postalCode ?? ''
    } as CustomerFormValues,
    validators: {
      onSubmit: customerSchema
    },
    onSubmit: async ({ value }) => {
      if (isEdit && customer) {
        await updateMutation.mutateAsync({ id: customer.id, values: value });
        return;
      }
      await createMutation.mutateAsync(value);
    }
  });

  useEffect(() => {
    if (!open) return;

    form.reset({
      code: customer?.code ?? '',
      name: customer?.name ?? '',
      taxId: customer?.taxId ?? '',
      email: customer?.email ?? '',
      phone: customer?.phone ?? '',
      customerType: customer?.customerType ?? 'developer',
      customerStatus: customer?.customerStatus ?? 'active',
      branchId: customer?.branchId ?? reference.branches[0]?.id ?? '',
      address: customer?.address ?? '',
      province: customer?.province ?? '',
      district: customer?.district ?? '',
      subDistrict: customer?.subDistrict ?? '',
      postalCode: customer?.postalCode ?? ''
    });
  }, [customer, form, open, reference.branches]);

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className='sm:max-w-2xl'>
        <SheetHeader>
          <SheetTitle>{isEdit ? 'แก้ไข Customer' : 'สร้าง Customer'}</SheetTitle>
          <SheetDescription>
            ใช้ mock form ตาม pattern เดิมของ repo และพร้อมสลับไป service จริงภายหลัง
          </SheetDescription>
        </SheetHeader>

        <div className='max-h-[calc(100vh-10rem)] overflow-auto pr-2'>
          <form.AppForm>
            <form.Form id='customer-form' className='grid gap-2 md:grid-cols-2'>
              <FormTextField name='code' label='Customer Code' required placeholder='CUS-BKK-006' />
              <FormTextField
                name='name'
                label='Customer Name'
                required
                placeholder='ALLA Distribution'
              />
              <FormTextField name='taxId' label='Tax ID' required placeholder='0105556...' />
              <FormTextField
                name='email'
                label='Email'
                required
                type='email'
                placeholder='contact@example.com'
              />
              <FormTextField name='phone' label='Phone' required placeholder='02-000-0000' />
              <FormSelectField
                name='customerType'
                label='Customer Type'
                required
                options={customerTypeOptions}
              />
              <FormSelectField
                name='customerStatus'
                label='Status'
                required
                options={customerStatusOptions.map((item) => ({
                  value: item.value,
                  label: item.label
                }))}
              />
              <FormSelectField
                name='branchId'
                label='Branch'
                required
                options={reference.branches.map((branch) => ({
                  value: branch.id,
                  label: branch.name
                }))}
              />
              <div className='md:col-span-2'>
                <FormTextField
                  name='address'
                  label='Address'
                  required
                  placeholder='123 Main Road'
                />
              </div>
              <FormTextField name='province' label='Province' required placeholder='Bangkok' />
              <FormTextField name='district' label='District' required placeholder='Chatuchak' />
              <FormTextField
                name='subDistrict'
                label='Sub District'
                required
                placeholder='Chom Phon'
              />
              <FormTextField name='postalCode' label='Postal Code' required placeholder='10900' />
            </form.Form>
          </form.AppForm>
        </div>

        <SheetFooter>
          <Button type='button' variant='outline' onClick={() => onOpenChange(false)}>
            ยกเลิก
          </Button>
          <Button type='submit' form='customer-form' isLoading={isPending}>
            {isEdit ? 'บันทึกการแก้ไข' : 'สร้าง Customer'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
