'use client';

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
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 { Icons } from '@/components/icons';
import type { PermissionTemplate } from '../api/types';
import {
  activatePermissionTemplateMutation,
  clonePermissionTemplateMutation,
  deactivatePermissionTemplateMutation,
  deletePermissionTemplateMutation
} from '../api/mutations';
import { PermissionTemplateFormSheet } from './permission-template-form-sheet';

export function PermissionTemplateRowActions({ data }: { data: PermissionTemplate }) {
  const [editOpen, setEditOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [toggleOpen, setToggleOpen] = useState(false);

  const cloneMutation = useMutation({
    ...clonePermissionTemplateMutation,
    onSuccess: () => {
      toast.success('Clone template เรียบร้อยแล้ว');
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถ clone template ได้');
    }
  });

  const deleteMutation = useMutation({
    ...deletePermissionTemplateMutation,
    onSuccess: () => {
      toast.success('ลบ Template เรียบร้อยแล้ว');
      setDeleteOpen(false);
    },
    onError: (error) => {
      toast.error(error.message || 'ไม่สามารถลบ Template ได้');
    }
  });

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

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

  const protectedTemplate = data.is_system;

  return (
    <>
      <PermissionTemplateFormSheet template={data} open={editOpen} onOpenChange={setEditOpen} />
      <AlertModal
        isOpen={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={() => deleteMutation.mutate({ id: data.id })}
        loading={deleteMutation.isPending}
      />
      <AlertModal
        isOpen={toggleOpen}
        onClose={() => setToggleOpen(false)}
        onConfirm={() =>
          data.is_active
            ? deactivateMutation.mutate({ id: data.id })
            : activateMutation.mutate({ id: data.id })
        }
        loading={activateMutation.isPending || deactivateMutation.isPending}
      />
      <DropdownMenu modal={false}>
        <DropdownMenuTrigger asChild>
          <Button variant='ghost' className='h-8 w-8 p-0'>
            <Icons.ellipsis className='h-4 w-4' />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align='end'>
          <DropdownMenuLabel>Actions</DropdownMenuLabel>
          <DropdownMenuItem onClick={() => setEditOpen(true)}>
            <Icons.edit className='mr-2 h-4 w-4' /> Edit
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => cloneMutation.mutate({ id: data.id })}>
            <Icons.page className='mr-2 h-4 w-4' />
            Clone
          </DropdownMenuItem>
          {!protectedTemplate ? (
            <DropdownMenuItem onClick={() => setToggleOpen(true)}>
              <Icons.settings className='mr-2 h-4 w-4' />
              {data.is_active ? 'Deactivate' : 'Activate'}
            </DropdownMenuItem>
          ) : null}
          {!protectedTemplate ? (
            <DropdownMenuItem onClick={() => setDeleteOpen(true)}>
              <Icons.trash className='mr-2 h-4 w-4' /> Soft Delete
            </DropdownMenuItem>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
