import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import { DateTimeStep } from './DateTimeStep';
import type { DateTimeStepValues, DateTimeStepErrors } from './DateTimeStep';
import { Navigation } from '../../organisms/Navigation';
import { StepIndicator } from '../../molecules/StepIndicator';
import { CartButton } from '../../molecules/CartButton';
import Box from '@mui/material/Box';

// ─── Helpers ─────────────────────────────────────────────────────────────────

const FALogo = () => (
  <Box sx={{ display: 'flex', alignItems: 'center' }}>
    <Box
      component="img"
      src="/brandlogo/logo-full.svg"
      alt="Funeral Arranger"
      sx={{ height: 28, display: { xs: 'none', md: 'block' } }}
    />
    <Box
      component="img"
      src="/brandlogo/logo-short.svg"
      alt="Funeral Arranger"
      sx={{ height: 28, display: { xs: 'block', md: 'none' } }}
    />
  </Box>
);

const nav = (
  <Navigation
    logo={<FALogo />}
    items={[
      { label: 'FAQ', href: '/faq' },
      { label: 'Contact Us', href: '/contact' },
    ]}
  />
);

const stepper = (
  <StepIndicator
    steps={[
      { label: 'Details' },
      { label: 'Venues' },
      { label: 'Coffins' },
      { label: 'Extras' },
      { label: 'Review' },
    ]}
    currentStep={0}
  />
);

const cart = (
  <CartButton
    total={4950}
    items={[{ section: 'Funeral Provider', name: 'H. Parsons — Essential Package', price: 4950 }]}
  />
);

const defaultValues: DateTimeStepValues = {
  firstName: '',
  surname: '',
  funeralDate: 'asap',
  preferredDates: [],
  funeralTime: 'no_preference',
};

// ─── Meta ────────────────────────────────────────────────────────────────────

const meta: Meta<typeof DateTimeStep> = {
  title: 'Pages/DateTimeStep',
  component: DateTimeStep,
  tags: ['autodocs'],
  parameters: {
    layout: 'fullscreen',
  },
};

export default meta;
type Story = StoryObj<typeof DateTimeStep>;

// ─── Interactive (default) — at-need ────────────────────────────────────────

/** At-need flow — all fields visible, grief-sensitive copy */
export const Default: Story = {
  render: () => {
    const [values, setValues] = useState<DateTimeStepValues>({ ...defaultValues });
    const [errors, setErrors] = useState<DateTimeStepErrors>({});

    const handleContinue = () => {
      const newErrors: DateTimeStepErrors = {};
      if (!values.firstName)
        newErrors.firstName = 'We need their first name for the funeral arrangements.';
      if (!values.surname)
        newErrors.surname = 'We need their surname for the funeral arrangements.';
      if (values.funeralDate === 'specific' && !values.preferredDates[0])
        newErrors.preferredDates = 'Please select at least one preferred date.';
      setErrors(newErrors);
      if (Object.keys(newErrors).length === 0)
        alert(`Continue: ${values.firstName} ${values.surname}`);
    };

    return (
      <DateTimeStep
        values={values}
        onChange={(v) => {
          setValues(v);
          setErrors({});
        }}
        onContinue={handleContinue}
        onBack={() => alert('Back')}
        onSaveAndExit={() => alert('Save and exit')}
        errors={errors}
        isAtNeed
        navigation={nav}
        progressStepper={stepper}
        runningTotal={cart}
      />
    );
  },
};

// ─── Pre-planning ───────────────────────────────────────────────────────────

/** Pre-planning flow — softer copy, helper text about updating later */
export const PrePlanning: Story = {
  render: () => {
    const [values, setValues] = useState<DateTimeStepValues>({ ...defaultValues });
    return (
      <DateTimeStep
        values={values}
        onChange={setValues}
        onContinue={() => alert('Continue')}
        onBack={() => alert('Back')}
        onSaveAndExit={() => alert('Save')}
        isAtNeed={false}
        navigation={nav}
      />
    );
  },
};

// ─── Specific dates selected ───────────────────────────────────────────────

/** Multiple preferred dates entered */
export const SpecificDates: Story = {
  render: () => {
    const [values, setValues] = useState<DateTimeStepValues>({
      ...defaultValues,
      firstName: 'Margaret',
      surname: 'Wilson',
      funeralDate: 'specific',
      preferredDates: ['2026-04-05', '2026-04-08'],
      funeralTime: 'morning',
    });
    return (
      <DateTimeStep
        values={values}
        onChange={setValues}
        onContinue={() => alert('Continue')}
        onBack={() => alert('Back')}
        isAtNeed
        navigation={nav}
      />
    );
  },
};

// ─── Name fields only ──────────────────────────────────────────────────────

/** Scheduling hidden — only name fields shown */
export const NameFieldsOnly: Story = {
  render: () => {
    const [values, setValues] = useState<DateTimeStepValues>({ ...defaultValues });
    return (
      <DateTimeStep
        values={values}
        onChange={setValues}
        onContinue={() => alert('Continue')}
        onBack={() => alert('Back')}
        showScheduling={false}
        navigation={nav}
      />
    );
  },
};

// ─── Validation errors ──────────────────────────────────────────────────────

/** All validation errors showing */
export const WithErrors: Story = {
  render: () => {
    const [values, setValues] = useState<DateTimeStepValues>({ ...defaultValues });
    return (
      <DateTimeStep
        values={values}
        onChange={setValues}
        onContinue={() => {}}
        errors={{
          firstName: 'We need their first name for the funeral arrangements.',
          surname: 'We need their surname for the funeral arrangements.',
        }}
        onBack={() => alert('Back')}
        navigation={nav}
      />
    );
  },
};

// ─── Loading ────────────────────────────────────────────────────────────────

/** Continue button in loading state */
export const Loading: Story = {
  render: () => {
    const [values, setValues] = useState<DateTimeStepValues>({
      ...defaultValues,
      firstName: 'Margaret',
      surname: 'Wilson',
      funeralDate: 'asap',
      funeralTime: 'morning',
    });
    return (
      <DateTimeStep
        values={values}
        onChange={setValues}
        onContinue={() => {}}
        loading
        navigation={nav}
      />
    );
  },
};
