'use client';
import { useCallback, useState } from 'react';
import moment, { Moment } from 'moment';
import { UseQueryResult } from '@tanstack/react-query';

import Icon from '@/components/Icon';
import { Button } from '@/components/UI/Button';
import { Datepicker } from '@/components/UI/Datepicker';
import { Radio } from '@/components/UI/Radio';
import { Select } from '@/components/UI/Select';
import { IOption } from '@/types/IOption';
import { Timepicker } from '@/components/UI/Timepicker';
import Tabs from '@/components/Tabs';
import { Checkbox } from '@/components/UI/Checkbox';
import Tags from '@/components/Tags';
import { useGetUserVehicleExForIndex } from '@/queries/records';
import { IValidationSchema, useForm } from '@/utils/useForm';

import { IGetUserVehicleExForIndexResponse } from '@/queries/records.interfaces';
import {
  recTypes,
  radioFilters,
  tabs,
  fileLocationOptions,
  fileTypesSelectOptions,
  addSelectionOptions,
} from './constants';

interface IRecordFilters {
  radioType: IOption['value'];
  name: IOption['value'];
  dateStart: IOption['value'];
  dateEnd: IOption['value'];
  fileLocation: IOption['value'];
  fileType: IOption['value'];
  recordType: IOption['value'];
  tags: string[];
}

interface IProps {
  onSearch: (filter: any) => void;
}

const init = {
  fileType: '2',
  fileLocation: '1',
  radioType: 'devices',
  recType: '-1',
};
const validation = {
  DevIDNO: [
    {
      check: (val) => !!val,
      message: 'Requied',
    },
  ],
  date: [
    {
      check: (val) => !!val,
      message: 'Requied',
    },
  ],
} as IValidationSchema;

export const Filters: React.FC<IProps> = ({ onSearch }) => {
  const [activeTab, setActiveTab] = useState<string>(tabs[0].key);

  const getUserVehicleExForIndex = useGetUserVehicleExForIndex();

  const handleSearch = useCallback(
    async (formData: any) => {
      onSearch?.({ ...formData });
    },
    [onSearch],
  );

  const form = useForm<any>(handleSearch, validation, init);

  return (
    <div className='bg-white rounded-xl p-4 min-w-[432px] shadow-[0px_1px_1px_#AFAFAF33] flex-[1]'>
      <div className='py-4 border-b-[1px] border-[#E6E9EE] mb-4'>
        <div className='flex items-center justify-between'>
          <Tabs value={activeTab} tabs={tabs} onChange={(key) => setActiveTab(key)} />
          <Button
            className='!size-10 !min-w-10 min-h-10 border-[1px] border-[#E6E9EE] flex items-center justify-center !rounded-lg'
            background='white'
          >
            <Icon src='/images/grid.svg' className='text-[#2981B3] w-6 h-6' />
          </Button>
        </div>
      </div>
      <form className='flex flex-col gap-4'>
        <SelectedTab
          form={form}
          tabId={activeTab}
          getUserVehicleExForIndex={getUserVehicleExForIndex}
        />
      </form>
    </div>
  );
};

interface ISelectedTab {
  form: any;
  tabId: string;
  getUserVehicleExForIndex: UseQueryResult<IGetUserVehicleExForIndexResponse, Error>;
}
const SelectedTab = ({ form, getUserVehicleExForIndex, tabId }: ISelectedTab) => {
  switch (tabId) {
    case tabs[0].key:
      return (
        <>
          <div className='flex items-center gap-[76px]'>
            {radioFilters.map((radioFilter) => (
              <Radio
                key={radioFilter.label}
                value={radioFilter.value}
                label={radioFilter.label}
                isActive={radioFilter.value === form.formData['radioType']}
                onChange={(value) => form.handleChangeField('radioType')(value)}
              />
            ))}
          </div>
          <div className='flex flex-col gap-[10px]'>
            <div className='flex items-center gap-3'>
              <Select
                placeholder={
                  form.formData['radioType'] === 'company' ? 'Название компании' : 'Название ТС'
                }
                value={form.formData['DevIDNO']}
                onChange={form.handleChangeField('DevIDNO')}
                options={
                  form.formData['radioType'] === 'devices'
                    ? getUserVehicleExForIndex.data?.vehicles?.map((item) => ({
                        label: item.nm,
                        value: item.dl[0].id.toString(),
                      }))
                    : getUserVehicleExForIndex.data?.infos?.map((item) => ({
                        label: item.name,
                        value: item.id,
                      })) || []
                }
                searchable
              />
              <Button
                className='max-w-[56px] w-[56px] flex justify-center items-center gap-[5px] border-[1px] border-light_gray'
                background='white'
                aria-label='Открыть'
                title='Открыть'
                type='button'
              >
                <span className='block w-[5px] h-[5px] rounded-[50%] bg-primary' />
                <span className='block w-[5px] h-[5px] rounded-[50%] bg-primary' />
                <span className='block w-[5px] h-[5px] rounded-[50%] bg-primary' />
              </Button>
            </div>
            <Datepicker
              onChange={(t) => form.handleChangeField('date')(moment(t))}
              open
              selected={(form.formData['date'] as Moment)?.toDate()}
            />
            <Timepicker
              label='Начало'
              placeholder='00:00:00'
              value={form.formData['start']}
              onChange={form.handleChangeField('start')}
            />
            <Timepicker
              label='Окончание'
              placeholder='23:59:00'
              value={form.formData['end']}
              onChange={form.handleChangeField('end')}
            />
            <Select
              label='Расположение файла'
              placeholder='Видеорегистратор'
              options={fileLocationOptions}
              value={form.formData['fileLocation']}
              onChange={form.handleChangeField('fileLocation')}
            />
            <Select
              label='Тип файла'
              placeholder='Видео'
              options={fileTypesSelectOptions}
              value={form.formData['fileType']}
              onChange={form.handleChangeField('fileType')}
            />
            <div>
              <p className='text-base leading-5 mb-3'>Тип файла</p>
              <div className='flex items-center justify-between'>
                {recTypes.map((fileType) => (
                  <Checkbox
                    key={fileType.label}
                    label={fileType.label}
                    value={fileType.value}
                    isActive={form.formData['radioType'] === fileType.value}
                    onChange={(value) => form.handleChangeField('radioType')(value)}
                    className='rounded-[50%]'
                  />
                ))}
              </div>
            </div>

            <Button type='submit' onClick={form.handleSubmit} disabled={!form.isValid}>
              Поиск
            </Button>
          </div>
        </>
      );
    case tabs[1].key:
      return (
        <>
          <div className='flex flex-col gap-3'>
            <Select
              placeholder={
                form.formData['radioType'] === 'company' ? 'Название компании' : 'Название ТС'
              }
              value={form.formData['DevIDNO']}
              onChange={form.handleChangeField('DevIDNO')}
              options={
                getUserVehicleExForIndex.data?.vehicles?.map((item) => ({
                  label: item.nm,
                  value: item.dl[0].id.toString(),
                })) || []
              }
            />
            <Datepicker
              onChange={(t) => form.handleChangeField('date')(moment(t))}
              open
              selected={(form.formData['date'] as Moment)?.toDate()}
            />
            <Timepicker
              label='Начало'
              placeholder='00:00:00'
              value={form.formData['start']}
              onChange={form.handleChangeField('start')}
            />
            <Timepicker
              label='Окончание'
              placeholder='23:59:00'
              value={form.formData['end']}
              onChange={form.handleChangeField('end')}
            />
            <div className='flex items-center gap-3'>
              <Select label='Пробег' placeholder='00км' />
              <Select label='Доп выбор' options={addSelectionOptions} placeholder='GPS' />
            </div>
            <Select label='Недопустимо' placeholder='Пункт' />
            <Select label='Стиль трека' placeholder='Пункт' />

            <Select label='Настройка трека' placeholder='Пункт' />

            <Button type='submit' onClick={form.handleSubmit} disabled={!form.isValid}>
              Поиск
            </Button>
          </div>
        </>
      );

    case tabs[2].key:
      return (
        <>
          <Select
            placeholder='Название ТС'
            value={form.formData['DevIDNO']}
            onChange={form.handleChangeField('DevIDNO')}
            options={
              getUserVehicleExForIndex.data?.vehicles?.map((item) => ({
                label: item.nm,
                value: item.dl[0].id.toString(),
              })) || []
            }
          />
          <Timepicker
            label='Начало'
            placeholder='00:00:00'
            value={form.formData['start']}
            onChange={form.handleChangeField('start')}
          />
          <Timepicker
            label='Окончание'
            placeholder='23:59:00'
            value={form.formData['end']}
            onChange={form.handleChangeField('end')}
          />
          <Button type='submit' onClick={form.handleSubmit} disabled={!form.isValid}>
            Поиск
          </Button>
        </>
      );
    default:
      break;
  }
};
