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

const API_URL = apiConfig.service_wallet;

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

  const doDeleteCurrency = useCallback(async () => {
    if (!selectedCurrency) {
      toast.error('No Currency selected');
      return;
    }
    // console.log(selectedCurrency);
    const response = await DeleteData(`${API_URL}/dashboard/currency/${selectedCurrency}`, {
      id: selectedCurrency
    });

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

      doSaveLogActivity(createActivity);
      reload();
    } else {
      setAlert({ show: true, message: response?.message });
      toast.error('Failed Delete Currency');
    }
  }, [selectedCurrency, DeleteData, handleDeleteDialog, reload]);
  // console.log(selectedCurrency);
  return (
    <Dialog open={showDeleteDialog} onOpenChange={(open) => handleDeleteDialog(open, null)}>
      <DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]: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={doDeleteCurrency}>
            Delete
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default DeleteDialog;
