import { useRef, useState } from 'react';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Alert, KeenIcon } from '@/components';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useManageMunicipiosContext } from '../hooks/useManageMunicipiosContext';
import { apiConfig } from '@/config/api.config';
import axios from 'axios';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';

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

const API_URL = apiConfig.service_master_data;

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

  const [formField, setFormField] = useState(initialState);
  const resetForm = () => {
    setFormField(initialState);
  };
  const [postoadms, setPostoadms] = useState<PostoAdmsProps[]>([]);
  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}/municipios/postoadms/${id}`);

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

  const handleReset = () => {
    setFormField(initialState);
    setIsFound(false);
    setPostoadms([]);
  };
  // console.log(municipios);
  return (
    <Dialog open={showSearchDialog} onOpenChange={(open) => handleSearchDialog(open)}>
      <DialogContent className="container-fixed max-w-[700px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogTitle></DialogTitle>
        <DialogDescription></DialogDescription>
        <DialogHeader className="p-2 border-0">
          <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 Postoadms
              </h1>
              <div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => {
                handleSearchDialog(false);
                resetForm();
              }}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
          <div className="flex flex-col px-0">
            {alert.show && (
              <Alert variant="danger" className="mb-5">
                {alert.message}
              </Alert>
            )}
            <form action="" onSubmit={handleSubmit}>
              <div className="card-body grid-cols-6 gap-5 p-0">
                <div className="grid grid-cols-8 gap-2 w-full items-center">
                  <label className="form-label flex items-center gap-1 col-span-2">
                    Municipio Name<span className="text-red-500">*</span>
                  </label>

                  <Select
                    value={formField.id.toString()}
                    onValueChange={(target) => {
                      const selectedMunicipio = municipios.find((m) => m.id.toString() === target);
                      if (selectedMunicipio) {
                        setFormField({
                          ...formField,
                          id: selectedMunicipio.id,
                          name: selectedMunicipio.name
                        });
                      }
                    }}
                  >
                    <SelectTrigger className="col-span-6">
                      <SelectValue placeholder="Select Municipios" />
                    </SelectTrigger>
                    <SelectContent>
                      {municipios.map((municipio) => (
                        <SelectItem key={municipio.id} value={municipio.id.toString()}>
                          {municipio.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

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

                <div className="flex justify-end pt-2.5 gap-5 col-span-6">
                  <Button variant={'outline'} type="reset" onClick={handleReset}>
                    Reset
                  </Button>
                  <Button variant={'default'} type="submit">
                    Search
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default SearchDialog;
