'use client';

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { AlertModal } from '@/components/modal/alert-modal';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { deleteLeadMutation } from '../api/mutations';
import type { LeadReferenceData, LeadSummary } from '../api/types';
import { LeadAssignmentDialog } from './lead-assignment-dialog';
import { LeadForm } from './lead-form';

export function LeadCellAction({
  data,
  referenceData,
  canUpdate,
  canDelete,
  canAssign
}: {
  data: LeadSummary;
  referenceData: LeadReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
  canAssign: boolean;
}) {
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [assignOpen, setAssignOpen] = useState(false);

  const deleteMutation = useMutation({
    ...deleteLeadMutation,
    onSuccess: () => {
      toast.success('ลบลีดสำเร็จ');
      setDeleteOpen(false);
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : 'ไม่สามารถลบลีดได้');
    }
  });

  return (
    <>
      <LeadForm open={editOpen} onOpenChange={setEditOpen} referenceData={referenceData} lead={data} />
      <LeadAssignmentDialog
        lead={data}
        referenceData={referenceData}
        open={assignOpen}
        onOpenChange={setAssignOpen}
      />
      <AlertModal
        isOpen={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate({ id: data.id })}
        loading={deleteMutation.isPending}
      />

      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button variant='ghost' className='h-8 w-8 p-0'>
            <span className='sr-only'>Open menu</span>
            <Icons.ellipsis className='h-4 w-4' />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align='end'>
          <DropdownMenuLabel>Actions</DropdownMenuLabel>
          {canUpdate ? (
            <DropdownMenuItem onClick={() => setEditOpen(true)}>Edit lead</DropdownMenuItem>
          ) : null}
          {canAssign ? (
            <DropdownMenuItem onClick={() => setAssignOpen(true)}>
              {data.assignedSalesOwnerId ? 'Reassign to sales' : 'Assign to sales'}
            </DropdownMenuItem>
          ) : null}
          {canDelete ? (
            <DropdownMenuItem className='text-destructive' onClick={() => setDeleteOpen(true)}>
              Delete lead
            </DropdownMenuItem>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
