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 => ${formField.name}`,
          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-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Municipio - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody>
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <form onSubmit={handleSubmit}>
              <div className="card-body grid gap-5">
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Municipio Name<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={formField.name}
                      onChange={(e) => setFormField({ ...formField, name: e.target.value })}
                    />
                  </div>
                </div>

                <div className="flex justify-end pt-2.5 gap-5">
                  <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;
