'use client';
import { AlertModal } from '@/components/modal/alert-modal';
import { useDeleteSurvey } from '@/feactures/surveys/hooks/use-mutation-surveys';
import { SurveyTable } from '@/feactures/surveys/schemas/survey';
import { Button } from '@repo/shadcn/button';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@repo/shadcn/tooltip';
import { Edit, Trash } from 'lucide-react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

interface CellActionProps {
  data: SurveyTable;
}

export const CellAction: React.FC<CellActionProps> = ({ data }) => {
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const { mutate: deleteSurvey } = useDeleteSurvey();
  const router = useRouter();
  const { data: session } = useSession();

  const onConfirm = async () => {
    try {
      setLoading(true);
      deleteSurvey(data.id!);
      setOpen(false);
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const role = session?.user.role[0]?.rol;

  return (
    <>
      <AlertModal
        isOpen={open}
        onClose={() => setOpen(false)}
        onConfirm={onConfirm}
        loading={loading}
        title="¿Estás seguro que desea eliminar la encuesta?"
        description="Esta acción no se puede deshacer."
      />

      <div className="flex gap-1">
        {['superadmin', 'admin'].includes(role ?? '') && (
          <>
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={() =>
                      router.push(
                        `/dashboard/administracion/encuestas/editar/${data.id!}`,
                      )
                    }
                  >
                    <Edit className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>Editar</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>

            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={() => setOpen(true)}
                  >
                    <Trash className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>Eliminar</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </>
        )}
      </div>
    </>
  );
};
