import { useRef, useState } from 'react';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Alert, KeenIcon } from '@/components';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import axios from 'axios';
import { useManageSucosContext } from '../hooks/useManageSucosContext';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

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

const API_URL = apiConfig.service_master_data;

const SearchDialog = () => {
  const parentRef = useRef<any | null>(null);
  const [open, setOpen] = useState(false);
  const { showSearchDialog, handleSearchDialog, sucos } = useManageSucosContext();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState = {
    id: 0,
    name: ''
  };

  const [formField, setFormField] = useState(initialState);
  const resetForm = () => {
    setFormField(initialState);
  };
  const [aldeia, setAldeia] = useState<AldeiasProps[]>([]);
  const [isFound, setIsFound] = useState(false);

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

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

    try {
      const response = await axios.get(`${API_URL}/postoadms/sucos/${id}`);

      if (response.data.status) {
        setAldeia(response.data.data);
        console.log(aldeia);
        setIsFound(true);
        console.log('Found Sucos: ', response.data.data);
      } else {
        setAldeia([]);
        setIsFound(false);
        setAlert({ show: true, message: 'No sucos found.' });
      }
    } catch (error) {
      console.error('Error fetching sucos', error);
      setAlert({ show: true, message: 'Failed to fetch sucos. Please try again.' });
    }
    setAlert({ show: false, message: '' });
  };

  const handleReset = () => {
    setFormField(initialState);
    setIsFound(false);
    setAldeia([]);
  };

  return (
    <Dialog open={showSearchDialog} onOpenChange={handleSearchDialog}>
      <DialogContent className="container-fixed max-w-[700px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogHeader className="p-2 border-0">
          <DialogTitle></DialogTitle>
          <DialogDescription></DialogDescription>
          <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">Search Aldeias</h1>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => {
                handleSearchDialog(false);
                handleReset();
              }}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
          <form onSubmit={handleSubmit} className="flex flex-col px-5 gap-5">
            {alert.show && <Alert variant="danger">{alert.message}</Alert>}

            <div className="grid grid-cols-8 gap-1 w-full items-center">
              <label className="form-label flex items-center col-span-3">
                Sucos Name<span className="text-red-500">*</span>
              </label>

              <Popover open={open} onOpenChange={setOpen}>
                <PopoverTrigger asChild>
                  <button type="button" className="input col-span-5 text-left">
                    {formField.name || 'Select Sucos'}
                  </button>
                </PopoverTrigger>
                <PopoverContent className="w-[400px] p-0">
                  <Command>
                    <CommandInput placeholder="Search Sucos..." />
                    <CommandList>
                      <CommandEmpty>No PostoAdms found.</CommandEmpty>
                      <CommandGroup>
                        {sucos.map((suco) => (
                          <CommandItem
                            key={suco.sucos_id}
                            value={suco.sucos_name}
                            onSelect={() => {
                              setFormField({
                                id: suco.sucos_id,
                                name: suco.sucos_name
                              });
                              setOpen(false);
                            }}
                          >
                            {suco.sucos_name}
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
            </div>

            {isFound && sucos.length > 0 && (
              <div className="mt-4 border-t pt-4">
                <h2 className="text-md font-semibold">Aldeias: </h2>
                <div className="flex flex-col">
                  <span className="text-sm form-hint">
                    {aldeia.map((aldeias) => aldeias.name).join(', ')}
                  </span>
                </div>
              </div>
            )}

            <div className="flex justify-end gap-4">
              <Button type="reset" variant="outline" onClick={handleReset}>
                Reset
              </Button>
              <Button type="submit" variant="default">
                Search
              </Button>
            </div>
          </form>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default SearchDialog;
