'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { AlertModal } from '@/components/modal/alert-modal';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { deleteEnquiryMutation } from '../api/mutations';
import type { EnquiryListItem, EnquiryReferenceData } from '../api/types';
import { EnquiryFormSheet } from './enquiry-form-sheet';

export function EnquiryCellAction({
  data,
  referenceData,
  canUpdate,
  canDelete
}: {
  data: EnquiryListItem;
  referenceData: EnquiryReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
}) {
  const router = useRouter();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);

  const deleteMutation = useMutation({
    ...deleteEnquiryMutation,
    onSuccess: () => {
      toast.success('Enquiry deleted successfully');
      setDeleteOpen(false);
    },
    onError: (error) =>
      toast.error(error instanceof Error ? error.message : 'Failed to delete enquiry')
  });

  return (
    <>
      <AlertModal
        isOpen={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate(data.id)}
        loading={deleteMutation.isPending}
      />
      <EnquiryFormSheet
        enquiry={data}
        open={editOpen}
        onOpenChange={setEditOpen}
        referenceData={referenceData}
      />
      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button variant='ghost' className='h-8 w-8 p-0'>
            <span className='sr-only'>Open actions</span>
            <Icons.ellipsis className='h-4 w-4' />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align='end'>
          <DropdownMenuLabel>Actions</DropdownMenuLabel>
          <DropdownMenuItem onClick={() => router.push(`/dashboard/crm/enquiries/${data.id}`)}>
            <Icons.arrowRight className='mr-2 h-4 w-4' /> View
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => setEditOpen(true)} disabled={!canUpdate}>
            <Icons.edit className='mr-2 h-4 w-4' /> Edit
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => setDeleteOpen(true)} disabled={!canDelete}>
            <Icons.trash className='mr-2 h-4 w-4' /> Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
