'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 { deleteCustomerMutation } from '../api/mutations';
import type { CustomerRecord, CustomerReferenceData } from '../api/types';
import { CustomerFormSheet } from './customer-form-sheet';

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

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

  return (
    <>
      <AlertModal
        isOpen={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate(data.id)}
        loading={deleteMutation.isPending}
      />
      <CustomerFormSheet
        customer={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>การดำเนินการ</DropdownMenuLabel>
          <DropdownMenuItem onClick={() => router.push(`/dashboard/crm/customers/${data.id}`)}>
            <Icons.arrowRight className='mr-2 h-4 w-4' /> ดูรายละเอียด
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => setEditOpen(true)} disabled={!canUpdate}>
            <Icons.edit className='mr-2 h-4 w-4' /> แก้ไข
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => setDeleteOpen(true)} disabled={!canDelete}>
            <Icons.trash className='mr-2 h-4 w-4' /> ลบ
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
