/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import { useEffect, useState } from 'react';

import { useTranslations } from 'next-intl';

import { Check, ChevronsUpDown } from 'lucide-react';
import { Control, Controller, UseFormSetValue, UseFormWatch } from 'react-hook-form';

import * as Field from '@/components/forms/Field';
import FormFieldError from '@/components/forms/FormFieldError';
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 { MAX_CUSTOM_LOCATION_LENGTH } from '@/lib/constants/eventSubmitFormContants';
import { EventFormValues } from '@/lib/schemas/eventSubmitFormSchema';
import { cn } from '@/lib/utils';

import { InstitutionListItem } from '@/types/Institutions';

interface StepDateAndLocationProps {
  control: Control<EventFormValues>;
  watch: UseFormWatch<EventFormValues>;
  setValue: UseFormSetValue<EventFormValues>;
  institutionList: InstitutionListItem[];
  errors: any;
}

export default function StepDateAndLocation({
  control,
  watch,
  setValue,
  institutionList,
  errors,
}: StepDateAndLocationProps) {
  const t = useTranslations('eventSubmit.stepDateAndLocation');
  const [institutionOpen, setInstitutionOpen] = useState(false);
  const useCustomLocation = watch('useCustomLocation');
  const isMultiDay = watch('isMultiDay');
  const startDate = watch('startDate');

  const getInstitutionLabel = (institution: InstitutionListItem) => {
    const showLocation = institution.intezmenyCimeMegjelenites === true;
    const location = showLocation && institution.telepules ? `, ${institution.telepules}` : '';
    return `${institution.nev}${location}`;
  };

  // Calculate tomorrow's date in local timezone
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0); // Set to start of day

  // Max date: end of next year
  const maxDate = new Date(new Date().getFullYear() + 1, 11, 31);

  // Minimum end date is the start date (or tomorrow if no start date)
  const minEndDate = startDate ? new Date(startDate) : tomorrow;

  useEffect(() => {
    if (!useCustomLocation) {
      setValue('customLocation', '');
    }
  }, [useCustomLocation, setValue]);

  useEffect(() => {
    if (!isMultiDay) {
      // Clear end date/time when unchecking
      setValue('endDate', '');
      setValue('endTime', '');
    }
  }, [isMultiDay, setValue]);

  return (
    <div className="grid gap-6">
      {/* Dates */}
      <div className="bg-white/70 p-5 sm:p-6">
        <Field.Wrapper label={t('dateTitle')} helper={t('dateSubtitle')} required>
          {/* Starting date + time in one row */}
          <div className="grid gap-4 lg:grid-cols-2">
            <Field.DatePicker
              control={control}
              name="startDate"
              placeholder={t('startDatePlaceholder')}
              required
              min={tomorrow}
              max={maxDate}
            />

            <Field.TimePicker control={control} name="startTime" clearable />
          </div>

          {/* Multi-day checkbox */}
          <Field.Checkbox control={control} name="isMultiDay" label={t('multiDayLabel')} />

          {/* End date + time (shown if multi-day) */}
          {isMultiDay && (
            <div className="grid gap-4 lg:grid-cols-2">
              <Field.DatePicker
                control={control}
                name="endDate"
                placeholder={t('endDatePlaceholder')}
                min={minEndDate}
                max={maxDate}
              />

              {/* <Field.TimePicker
                control={control}
                name="endTime"
                clearable
              /> */}
            </div>
          )}
        </Field.Wrapper>
      </div>

      {/* Location */}
      <div className="bg-white/70 p-5 sm:p-6">
        <Field.Wrapper label={t('locationTitle')} helper={t('locationSubtitle')} required>
          {/* Institution Selector */}
          <div>
            <Controller
              name="selectedInstitution"
              control={control}
              render={({ field }) => (
                <Popover open={institutionOpen} onOpenChange={setInstitutionOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      aria-expanded={institutionOpen}
                      className="w-full justify-between h-11 text-base font-normal rounded-none border border-[#151720]/20 bg-white/80 text-[#151720] shadow-none hover:border-[#151720]/40 hover:bg-white"
                    >
                      {(() => {
                        const selectedInstitution = institutionList.find(
                          (inst) => inst.id === field.value
                        );
                        return selectedInstitution
                          ? getInstitutionLabel(selectedInstitution)
                          : t('institutionPlaceholder');
                      })()}
                      <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-full p-0" align="start">
                    <Command>
                      <CommandInput placeholder={t('searchInstitutionPlaceholder')} />
                      <CommandEmpty>{t('noInstitutionFound')}</CommandEmpty>
                      <CommandGroup className="max-h-[300px] overflow-y-auto">
                        {institutionList?.map((institution) => (
                          <CommandItem
                            key={institution.id}
                            value={`${institution.nev} ${institution.rovidites ?? ''}`.trim()}
                            onSelect={() => {
                              field.onChange(institution.id);
                              setInstitutionOpen(false);
                              setValue('useCustomLocation', false);
                            }}
                          >
                            <Check
                              className={cn(
                                'mr-2 h-4 w-4',
                                field.value === institution.id ? 'opacity-100' : 'opacity-0'
                              )}
                            />
                            {getInstitutionLabel(institution)}
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
              )}
            />
            {/* temp placeholder div */}
            <div className="mb-2"></div>

            {errors.selectedInstitution && (
              <FormFieldError message={errors.selectedInstitution.message} />
            )}
          </div>

          {/* Custom Location Toggle */}
          <Field.Checkbox
            control={control}
            name="useCustomLocation"
            label={t('customLocationLabel')}
          />

          {/* Custom Location Input */}
          {useCustomLocation && (
            <Field.Input
              control={control}
              name="customLocation"
              helper={t('customLocationHelper')}
              placeholder={t('customLocationPlaceholder')}
              maxLength={MAX_CUSTOM_LOCATION_LENGTH}
            />
          )}
        </Field.Wrapper>
      </div>
    </div>
  );
}
