'use client';

import { useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import { createMasterOptionMutation } from '../api/mutations';
import { masterOptionsQueryOptions } from '../api/queries';
import type { MasterOptionMutationPayload } from '../api/types';
import { MasterOptionsFormDialog } from './master-options-form-dialog';

export function MasterOptionsCreateAction() {
  const [open, setOpen] = useState(false);
  const { data } = useQuery(masterOptionsQueryOptions({ page: 1, limit: 200 }));
  const createMutation = useMutation({
    ...createMasterOptionMutation,
    onSuccess: () => {
      toast.success('Master option created.');
      setOpen(false);
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'Create failed');
    }
  });

  async function handleSubmit(values: MasterOptionMutationPayload) {
    await createMutation.mutateAsync(values);
  }

  return (
    <>
      <Button onClick={() => setOpen(true)}>
        <Icons.add className='mr-2 h-4 w-4' />
        Add Option
      </Button>
      <MasterOptionsFormDialog
        open={open}
        onOpenChange={setOpen}
        onSubmit={handleSubmit}
        pending={createMutation.isPending}
        availableParents={data?.items ?? []}
      />
    </>
  );
}
