'use client';

import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
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 { createOrganizerMutation, updateOrganizerMutation } from '../api/mutations';
import type { Organizer } from '../api/types';
import { type OrganizerFormValues, organizerSchema } from '../schemas/organizer';

interface OrganizerFormSheetProps {
  organizer?: Organizer;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function OrganizerFormSheet({ organizer, open, onOpenChange }: OrganizerFormSheetProps) {
  const isEdit = !!organizer;

  const createMutation = useMutation({
    ...createOrganizerMutation,
    onSuccess: () => {
      toast.success('สร้าง organizer เรียบร้อยแล้ว');
      onOpenChange(false);
      form.reset();
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถสร้าง organizer ได้');
    }
  });

  const updateMutation = useMutation({
    ...updateOrganizerMutation,
    onSuccess: () => {
      toast.success('อัปเดต organizer เรียบร้อยแล้ว');
      onOpenChange(false);
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถอัปเดต organizer ได้');
    }
  });

  const form = useAppForm({
    defaultValues: {
      name: organizer?.name ?? ''
    } as OrganizerFormValues,
    validators: {
      onSubmit: organizerSchema
    },
    onSubmit: async ({ value }) => {
      if (isEdit && organizer) {
        await updateMutation.mutateAsync({
          id: organizer.id,
          values: value
        });
        return;
      }

      await createMutation.mutateAsync(value);
    }
  });

  const { FormTextField } = useFormFields<OrganizerFormValues>();
  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className='flex flex-col'>
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit Organizer' : 'Create Organizer'}</SheetTitle>
          <SheetDescription>
            {isEdit
              ? 'Update the organizer name without changing existing training data.'
              : 'Create a new organizer workspace and seed its master data.'}
          </SheetDescription>
        </SheetHeader>

        <div className='flex-1 overflow-auto'>
          <form.AppForm>
            <form.Form id='organizer-form-sheet' className='space-y-4'>
              <FormTextField
                name='name'
                label='Organizer Name'
                required
                placeholder='Acme Training Center'
              />
            </form.Form>
          </form.AppForm>
        </div>

        <SheetFooter>
          <Button type='button' variant='outline' onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button type='submit' form='organizer-form-sheet' isLoading={isPending}>
            <Icons.check /> {isEdit ? 'Update Organizer' : 'Save Organizer'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
