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

const API_URL = apiConfig.service_master_data;

const EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedMunicipios, municipios } =
    useManageMunicipiosContext();
  const { reload } = useDataGrid();
  const { PutData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const initialState = {
    name: '',
    updated_by: '',
    updated_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 doUpdateMunicipios = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      const response = await PutData(
        `${API_URL}/municipios/update/${selectedMunicipios}`,
        formField
      );

      if (response?.status) {
        handleEditDialog(false, null);
        resetForm();
        toast.success('Success update municipio');
        reload();
        const createActivity = {
          module: 'Manage Municipios',
          description: `Edit Municipio => ${selectedMunicipios}`,
          action: 'U'
        };

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

  const doFetchData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/municipios/getdata/${id}`, { id });

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response.data.name
      }));
    } else {
      setFormField((prev) => ({
        ...prev,
        name: ''
      }));
    }
  }, []);

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

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

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

  useEffect(() => {
    if (selectedMunicipios) {
      doFetchData(selectedMunicipios);
    }
  }, [selectedMunicipios]);

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

  useEffect(() => {
    if (selectedMunicipios) {
      setFormField({
        name: formField.name,
        updated_by: parsedUser.email,
        updated_at: formattedTime
      });
    }
  }, [formattedTime]);

  // console.log(selectedMunicipios);
  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Municipio - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody>
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <form onSubmit={handleUpdate}>
              <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">
                  <Button className="btn btn-primary">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
