import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import axios from 'axios';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import { getAuth, useAuthContext } from '@/auth';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';

const API_URL = apiConfig.service_master_data;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { reload } = useDataGrid();
  const { PostData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const { showAddDialog, handleAddDialog, selectedMunicipios } = useManageMunicipiosContext();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    name: '',
    created_by: '',
    created_at: ''
  };

  const [formField, setFormField] = useState(initialState);
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');

  const resetForm = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
  };

  const doCreateMunicipio = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      const response = await PostData(`${API_URL}/municipios/create`, formField);

      if (response?.status) {
        handleAddDialog(false);
        resetForm();
        reload();
        toast.success('Municipio created successfully!');
        const createActivity = {
          module: 'Manage Municipio',
          description: `Create Municipio => ${selectedMunicipios}`,
          action: 'C'
        };

        doSaveLogActivity(createActivity);
      } else {
        toast.error('Failed to create municipio.');
        setAlert({ show: true, message: 'Failed to create municipio. Please try again.' });
      }
    },
    [formField]
  );

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (formField.name.trim() === '') {
      setAlert({ show: true, message: 'Please fill name field.' });
      return;
    }

    doCreateMunicipio(e);
    console.log(parsedUser.email);
    console.log(formField);
    setAlert({ show: false, message: '' });
  };

  const handleReset = () => {
    resetForm();
    setAlert({ show: false, message: '' });
  };

  useEffect(() => {
    if (showAddDialog) {
      setFormField({
        name: formField.name,
        created_by: parsedUser?.username,
        created_at: formattedTime
      });
    }
  }, [formattedTime]);

  useEffect(() => {
    if (showAddDialog === false) {
      resetForm();
    }
  }, [showAddDialog]);

  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <DialogContent className="container-fixed max-w-96 flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogTitle></DialogTitle>
        <DialogDescription></DialogDescription>
        <DialogHeader className="p-2 border-0">
          <div className="flex items-center justify-between flex-wrap grow">
            <div className="flex flex-col justify-center">
              <h1 className="text-xl font-semibold leading-none text-gray-900">Add Municipios</h1>
              <div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => {
                handleAddDialog(false);
                resetForm();
              }}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
          <div className="flex flex-col px-0">
            {alert.show && (
              <Alert variant="danger" className="mb-5">
                {alert.message}
              </Alert>
            )}
            <form action="" onSubmit={handleSubmit}>
              <div className="card-body grid-cols-6 gap-5 p-0">
                <div className="grid grid-cols-8 gap-2 w-full items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Name<span className="text-red-500">*</span>
                  </label>

                  <Input
                    className="input col-span-6"
                    type="text"
                    autoComplete="off"
                    value={formField.name}
                    onChange={({ target }) =>
                      setFormField((prev) => ({ ...prev, name: target.value }))
                    }
                  />
                </div>

                <div className="flex justify-end pt-2.5 gap-5 col-span-6">
                  <Button variant={'outline'} type="reset" onClick={handleReset}>
                    Reset
                  </Button>
                  <Button variant={'default'} type="submit">
                    Create
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
