import { apiConfig } from '@/config/api.config';
import { useManageAldeiasContext } from '../hooks/useManageAldeiasContext';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
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';

interface SucosProps {
  sucos_id: number;
  sucos_name: string;
}

const API_URL = apiConfig.service_master_data;

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showAddDialog, handleAddDialog, selectedAldeias } = useManageAldeiasContext();
  const { reload } = useDataGrid();
  const { PostData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const [sucos, setSucos] = useState<SucosProps[]>([]);
  const [open, setOpen] = useState(false);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    name: '',
    sucosId: 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);
    setAlert({ show: false, message: '' });
  };

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

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

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

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

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

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

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

    if (formField.name === '' || formField.sucosId === 0) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

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

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

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

  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>Aldeia - 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">
                      Aldeia 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="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">
                      Sucos ID<span className="text-red-500">*</span>
                    </label>
                    <Popover open={open} onOpenChange={setOpen}>
                      <PopoverTrigger asChild>
                        <button
                          type="button"
                          className="input col-span-5 text-left"
                          style={{ color: 'inherit' }}
                        >
                          {sucos.find((suco) => suco.sucos_id === formField.sucosId)?.sucos_name ||
                            'Select Sucos'}
                        </button>
                      </PopoverTrigger>
                      <PopoverContent
                        className="w-[400px] p-0"
                        onWheel={(e) => e.stopPropagation()}
                      >
                        <Command>
                          <CommandInput placeholder="Search Sucos..." />
                          <CommandList>
                            <CommandEmpty>No Sucos found.</CommandEmpty>
                            <CommandGroup>
                              {sucos.map((suco) => (
                                <CommandItem
                                  key={suco.sucos_id}
                                  value={suco.sucos_name}
                                  onSelect={() => {
                                    setFormField({
                                      ...formField,
                                      sucosId: suco.sucos_id
                                    });
                                    setOpen(false);
                                  }}
                                >
                                  {suco.sucos_name}
                                </CommandItem>
                              ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default">Save Changes</Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
