import { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { Divider, Stack } from '@mui/material';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { type Meta, type StoryObj } from '@storybook/react-vite';

import FormTimePicker from './form';
import TimePicker from './index';

const meta: Meta<typeof TimePicker> = {
  title: 'Composed Components/Inputs/TimePicker',
  component: TimePicker,
  tags: ['autodocs'],
  args: {
    label: 'Label',
    helperText: 'Helper',
    placeholder: 'hh:mm',
    value: null,
  },
  render: props => {
    const [value, setValue] = useState<Date | null>(props.value);

    return (
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <TimePicker
          {...props}
          value={value}
          onChange={setValue}
        />
      </LocalizationProvider>
    );
  },
};

export default meta;

type Story = StoryObj<typeof TimePicker>;

export const Default: Story = {
  args: {
    label: 'Label',
    helperText: 'Helper',
    placeholder: 'hh:mm',
    sx: { width: 300 },
  },
};

export const Timezone: Story = {
  args: {
    label: 'Label',
    helperText: 'Helper',
    placeholder: 'hh:mm',
    timezone: 'Asia/Anadyr',
    disablePast: true,
    sx: { width: 300 },
  },
};

export const WithValue: Story = {
  args: {
    label: 'Select time',
    helperText: 'Choose a time',
    placeholder: 'hh:mm',
    value: new Date(2024, 0, 1, 14, 30),
  },
};

export const Small: Story = {
  args: {
    label: 'Small time picker',
    size: 'small',
    placeholder: 'hh:mm',
  },
};

export const Disabled: Story = {
  args: {
    label: 'Disabled time picker',
    disabled: true,
    placeholder: 'hh:mm',
  },
};

export const Error: Story = {
  args: {
    label: 'Time with error',
    errorText: 'This field is required',
    error: true,
    placeholder: 'hh:mm',
  },
};

export const FullWidth: Story = {
  args: {
    label: 'Full width',
    helperText: 'Helper text',
    fullWidth: true,
    placeholder: 'hh:mm',
  },
};

export const MinutesStep5: Story = {
  args: {
    label: 'Minutes step: 5 (default)',
    helperText: 'Minutes go from 5 to 5 (0, 5, 10, 15, 20...)',
    minutesStep: 5,
    placeholder: 'hh:mm',
    sx: { width: 300 },
  },
};

export const NoIcon: Story = {
  args: {
    label: 'Without clock icon',
    helperText: 'Only manual input, no dropdown',
    placeholder: 'hh:mm',
    noIcon: true,
    sx: { width: 300 },
  },
};

// ============================================================================
// FORM STORIES
// ============================================================================

type FormStory = StoryObj<typeof FormTimePicker>;

export const FormTimePickerDefault: FormStory = {
  render: () => {
    const form = useForm({
      defaultValues: {
        time: null,
      },
    });
    const { watch } = form;

    return (
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <span>Form:</span>
        <pre>{JSON.stringify(watch(), null, 2)}</pre>
        <Divider sx={{ my: 2 }} />
        <FormProvider {...form}>
          <FormTimePicker
            name="time"
            inputProps={{
              label: 'Label',
              helperText: 'Helper',
              placeholder: 'hh:mm',
              sx: { width: 300 },
            }}
          />
        </FormProvider>
      </LocalizationProvider>
    );
  },
};

export const FormTimePickerWithReferenceDate: FormStory = {
  render: () => {
    const form = useForm({
      defaultValues: {
        time: null,
      },
    });
    const { watch } = form;

    const referenceDate = new Date('2025-10-01T00:00:00');

    return (
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <span>Form:</span>
        <pre>{JSON.stringify(watch(), null, 2)}</pre>
        <Divider sx={{ my: 2 }} />
        <FormProvider {...form}>
          <FormTimePicker
            name="time"
            inputProps={{
              label: 'Select time',
              helperText: 'Reference date: 01/10/2025',
              placeholder: 'hh:mm',
              referenceDate,
            }}
          />
        </FormProvider>
      </LocalizationProvider>
    );
  },
};

const currentDateAt14hs = () => {
  const date = new Date();
  date.setHours(14, 0, 0, 0);
  return date;
};

export const FormTimePickerError: FormStory = {
  render: () => {
    const form = useForm({
      defaultValues: {
        time: null,
      },
      mode: 'onChange',
    });
    const { watch } = form;

    return (
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <pre>{JSON.stringify(watch(), null, 2)}</pre>
        <Divider sx={{ my: 2 }} />
        <FormProvider {...form}>
          <Stack sx={{ flexDirection: 'row', gap: 2 }}>
            <FormTimePicker
              name="time"
              inputProps={{
                label: 'With error text',
                placeholder: 'hh:mm',
                helperText: 'Chose an hour before 14:00',
              }}
              rules={{
                validate: {
                  timeBefore14hs: (value: Date) =>
                    value < currentDateAt14hs() || 'Hour must be before 14:00',
                },
              }}
            />
            <FormTimePicker
              name="time"
              inputProps={{
                label: 'Without error text',
                placeholder: 'hh:mm',
                helperText: 'Chose an hour before 14:00',
                hideErrorText: true,
              }}
              rules={{
                validate: {
                  timeBefore14hs: (value: Date) =>
                    value < currentDateAt14hs() || 'Hour must be before 14:00',
                },
              }}
            />
          </Stack>
        </FormProvider>
      </LocalizationProvider>
    );
  },
};
