import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useManagePostoAdmsContext } from '../hooks/useManagePostoAdmsContext';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth, useAuthContext } from '@/auth';
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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';

interface MunicipioProps {
  id: number;
  name: string;
}

const API_URL = apiConfig.service_master_data;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog, selectedPostoAdms } = useManagePostoAdmsContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [municipios, setMunicipios] = useState<MunicipioProps[]>([]);
  const [open, setOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const initialState = {
    name: '',
    municipio_id: 0,
    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);
    setErrors({});
  };

  const validateForm = () => {
    const requiredFields = [
      { key: 'name', label: 'Postu Administrativo Name' },
      { key: 'municipio_id', label: 'Municipio Name' }
    ];
    const newErrors: Record<string, string> = {};
    let isValid = true;
  
    requiredFields.forEach(({ key, label }) => {
      const value = formField[key as keyof typeof formField];
      const isEmpty = value === '' || value === null || value === undefined || value === 0;
      if (isEmpty) {
        newErrors[key] = `${label} is required`;
        toast.error(`${label} is required`);
        isValid = false;
      }
    });
  
    setErrors(newErrors);
    return isValid;
  };
  

  const doCreatePostoAdm = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setIsSubmitting(true);

      try {
        const response = await PostData(`${API_URL}/postoadms/create`, formField);

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

          doSaveLogActivity(createActivity);
        } else {
          toast.error('Failed to create Postu Administrativo. Please try again.');
          setAlert({
            show: true,
            message: response?.message
          });
        }
      } catch (error) {
        toast.error('Something went wrong. Please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField]
  );

  const doFetchMunicipios = async (sorting: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      const response = await GetData(`${API_URL}/municipios/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });

      // console.log(response?.data);
      setMunicipios(response?.data.list);
    } catch (error) {
      console.error('Error fetching Municipio', error);
      setAlert({ show: true, message: 'Failed to get Municipio. Please try again.' });
    }
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitting(true);
    if (!validateForm()) {
      setIsSubmitting(false);
      return;
    }
    doCreatePostoAdm(e);
  };

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

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

  useEffect(() => {
    doFetchMunicipios([{ id: 'name', desc: false }]);
  }, []);

  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Postu Administrativo - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef}>
          <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">
                      Posto Administrativo Name
                      <span className="text-red-500">*</span>
                    </label>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.name ? 'border-red-500' : ''}`}
                        type="text"
                        autoComplete="off"
                        value={formField.name}
                        onChange={({ target }) => {
                          setFormField((prev) => ({ ...prev, name: target.value }));
                          if (target.value) {
                            setErrors((prev) => ({ ...prev, name: '' }));
                          }
                        }}
                      />
                      {errors.name && <span className="text-red-500 text-xs mt-1">{errors.name}</span>}
                    </div>
                  </div>
                </div>

                <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>
                    <div className="grow flex flex-col">
                      <Popover open={open} onOpenChange={setOpen}>
                        <PopoverTrigger asChild>
                          <button
                            type="button"
                            className={`input text-left ${errors.municipio_id ? 'border-red-500' : ''}`}
                          >
                            {municipios.find((municipio) => municipio.id === formField.municipio_id)
                              ?.name || 'Select Municipio'}
                          </button>
                        </PopoverTrigger>
                        <PopoverContent
                          className="w-[400px] p-0"
                          onWheel={(e) => e.stopPropagation()}
                        >
                          <Command>
                            <CommandInput placeholder="Search Municipio..." />
                            <CommandList className="max-h-[300px] overflow-y-auto pointer-events-auto">
                              <CommandEmpty>No Municipio found.</CommandEmpty>
                              <CommandGroup>
                                {municipios.map((municipio) => (
                                  <CommandItem
                                    key={municipio.id}
                                    value={municipio.name}
                                    onSelect={() => {
                                      setFormField({ ...formField, municipio_id: municipio.id });
                                      setErrors((prev) => ({ ...prev, municipio_id: '' }));
                                      setOpen(false);
                                    }}
                                  >
                                    {municipio.name}
                                  </CommandItem>
                                ))}
                              </CommandGroup>
                            </CommandList>
                          </Command>
                        </PopoverContent>
                      </Popover>
                      {errors.municipio_id && (
                        <span className="text-red-500 text-xs mt-1">{errors.municipio_id}</span>
                      )}
                    </div>
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default" type="submit" disabled={isSubmitting}>
                    {isSubmitting ? (
                      <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                    ) : (
                      'Create'
                    )}
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
