'use client';

import { useState } from 'react';
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 { softDeleteOrganizerMutation } from '../api/mutations';
import type { Organizer } from '../api/types';
import { OrganizerFormSheet } from './organizer-form-sheet';

interface OrganizerCardActionsProps {
  organizer: Organizer;
}

export function OrganizerCardActions({ organizer }: OrganizerCardActionsProps) {
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);

  const deleteMutation = useMutation({
    ...softDeleteOrganizerMutation,
    onSuccess: () => {
      toast.success('ปิดการใช้งาน organizer เรียบร้อยแล้ว');
      setDeleteOpen(false);
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถปิดการใช้งาน organizer ได้');
    }
  });

  return (
    <>
      <AlertModal
        isOpen={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate(organizer.id)}
        loading={deleteMutation.isPending}
        title='ยืนยันการปิดใช้งาน Organizer'
        description='Organizer นี้จะไม่ถูกลบออกจากฐานข้อมูล แต่จะไม่สามารถใช้งานหรือถูกเลือกจากระบบได้อีก'
        confirmLabel='Delete'
      />
      <OrganizerFormSheet organizer={organizer} open={editOpen} onOpenChange={setEditOpen} />
      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button variant='ghost' className='h-8 w-8 p-0'>
            <span className='sr-only'>Open organizer actions</span>
            <Icons.ellipsis className='h-4 w-4' />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align='end' sideOffset={8} className='w-44'>
          <DropdownMenuLabel>Actions</DropdownMenuLabel>
          <DropdownMenuItem onClick={() => setEditOpen(true)}>
            <Icons.edit className='mr-2 h-4 w-4' /> Edit
          </DropdownMenuItem>
          <DropdownMenuItem
            onClick={() => setDeleteOpen(true)}
            className='text-destructive focus:text-destructive'
          >
            <Icons.trash className='mr-2 h-4 w-4' /> Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
