import { apiConfig } from '@/config/api.config';
import { useManageProfessionContext } from '../hooks/useManageProfessionContext';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { useCallback, useState } from 'react';
import { toast } from 'sonner';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { doSaveLogActivity } from '@/actions/GlobalActions';

const API_URL = apiConfig.service_master_data;

const DeleteDialog = () => {
  const { showDeleteDialog, handleDeleteDialog, selectedProfession } = useManageProfessionContext();
  const { reload } = useDataGrid();
  const { DeleteData } = useCallApi();
  const [alert, setAlert] = useState({ show: false, message: '' });

  const doDeleteProfession = useCallback(async () => {
    if (!selectedProfession) {
      toast.error('No profession selected');
      return;
    }
    const response = await DeleteData(`${API_URL}/profession/delete/${selectedProfession}/false`, {
      id: selectedProfession
    });

    if (response?.status) {
      setAlert({ show: false, message: '' });
      handleDeleteDialog(false, null);
      toast.success('Success Delete Profession');
      reload();
      const createActivity = {
        module: 'Manage Profession',
        description: `Delete Profession', => ${selectedProfession}`,
        action: 'D'
      };

      doSaveLogActivity(createActivity);
    } else {
      setAlert({ show: true, message: response?.message });
      toast.error('Failed Delete Profession');
    }
  }, [selectedProfession, DeleteData, handleDeleteDialog, reload]);

  return (
    <Dialog open={showDeleteDialog} onOpenChange={(open) => handleDeleteDialog(open, null)}>
      <DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden">
        <DialogHeader className="p-0 border-0 block">
          <DialogTitle></DialogTitle>
          <DialogDescription></DialogDescription>
          <Alert variant="warning">
            <h3 className="text-lg">Are you sure?</h3>
            <span className="text-sm">You will delete this data!</span>
          </Alert>
          {alert.show && (
            <Alert variant="danger">
              <h3>{alert.message}</h3>
            </Alert>
          )}
        </DialogHeader>
        <DialogFooter className="flex justify-end items-center gap-4 mt-3">
          <Button variant="outline" onClick={() => handleDeleteDialog(false, null)}>
            Cancel
          </Button>
          <Button variant="destructive" onClick={doDeleteProfession}>
            Delete
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default DeleteDialog;
