import { Button } from '@/components/ui/button';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from '@/components/ui/command';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { FormElement } from '@/types/form-types';
import { useEffect, useMemo, useState } from 'react';

interface Option {
  value: string | number;
  label: string;
  id: string | number;
}

interface FormSelectProps {
  form: any;
  element: FormElement;
  field: {
    value: string | number;
    onChange: (value: string | number) => void;
  };
  dropdownOptions?: Array<{ id: string | number; label: string }>;
  defaultValue?: unknown;
}

export const FormSelectPopover = ({
  form,
  element,
  field,
  dropdownOptions,
  defaultValue,
}: FormSelectProps) => {
  const [isOpen, setIsOpen] = useState(false);

  const options: Option[] = useMemo(() => {
    if (element?.options?.length) {
      return element.options.map((opt) => ({
        value: String(opt.id),
        label: opt.label,
        id: String(opt.id),
      }));
    }
    if (dropdownOptions?.length) {
      return dropdownOptions.map((option) => ({
        value: String(option.id),
        label: option.label,
        id: String(option.id),
      }));
    }
    return [];
  }, [element?.options, dropdownOptions]);

  const selectedOption = useMemo(() => {
    const currentValue = String(field.value) ?? '';
    return options.find((opt) => String(opt.id) === currentValue);
  }, [options, field.value]);

  const handlePropsOnChange = (
    element: FormElement,
    selectedValue: string | number,
  ) => {
    if (element.props?.onchange) {
      const { required_fields, child_element_id } = element.props.onchange;

      // Check if all required fields have values
      const allRequiredFieldsHaveValues = required_fields?.every(
        (fieldName) => {
          const fieldValue = form.watch(fieldName);
          return (
            fieldValue !== undefined && fieldValue !== null && fieldValue !== ''
          );
        },
      );

      console.log(
        `OnChange triggered for parent_element_id: ${form.watch('client_from_country_id')}, child_element_id: ${child_element_id}, selectedValue: ${selectedValue}`,
      );

      console.log(
        `All required fields have values: ${allRequiredFieldsHaveValues}`,
      );

      // You can use this boolean for further logic
      if (allRequiredFieldsHaveValues) {
        // Execute your custom logic when all required fields are filled
        console.log(
          'All required fields are filled, executing additional logic...',
        );
        // Add your custom logic here
      } else {
        console.log('Some required fields are missing values');
      }
    }
  };

  useEffect(() => {
    if (!field.value && defaultValue) {
      field.onChange(String(defaultValue));
    }
  }, [defaultValue, field]);

  return (
    <Popover open={isOpen} onOpenChange={setIsOpen} modal>
      <PopoverTrigger asChild>
        <Button
          className="w-full text-left flex justify-between"
          variant="outline"
          aria-expanded={isOpen}
          type="button"
        >
          {selectedOption?.label || 'Choose Option'}
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="lucide lucide-chevron-down h-4 w-4 opacity-50"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6"></path>
          </svg>
        </Button>
      </PopoverTrigger>
      <PopoverContent className="p-0 z-[9999]">
        <Command>
          <CommandInput placeholder="Search options..." className="h-9" />
          <CommandEmpty>No options found</CommandEmpty>
          <CommandGroup>
            {options.map((item) => (
              <CommandItem
                key={item.id}
                onSelect={() => {
                  field.onChange(String(item.id));
                  setIsOpen(false);
                  handlePropsOnChange(element, String(item.id));
                }}
                aria-selected={String(item.id) === String(field.value)}
                className="cursor-pointer"
              >
                <span
                  className={
                    String(item.id) === String(field.value)
                      ? 'font-semibold'
                      : ''
                  }
                >
                  {item.label}
                </span>
              </CommandItem>
            ))}
          </CommandGroup>
        </Command>
      </PopoverContent>
    </Popover>
  );
};
