/**
 * @fileoverview Storybook stories for the SearchableSimple Dropdown component.
 * These stories showcase the various states, themes, and styling capabilities of the SearchableSimple Dropdown field.
 * The SearchableSimple Dropdown component provides dropdown selection with search functionality but without history.
 */
import React, { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react'
import { userEvent, within, expect } from '@storybook/test'
import SearchableSimple, { DropdownOption } from './index'

// Sample data for dropdowns
const sampleOptions = [
  { value: 'apple' },
  { value: 'banana' },
  { value: 'cherry' },
  { value: 'date' },
  { value: 'elderberry' },
  { value: 'fig' },
  { value: 'grape' },
  { value: 'honeydew' },
]

const countryOptions = [
  { value: 'us' },
  { value: 'ca' },
  { value: 'uk' },
  { value: 'au' },
  { value: 'de' },
  { value: 'fr' },
  { value: 'jp' },
  { value: 'in' },
  { value: 'br' },
  { value: 'mx' },
]

// Wrapper component for state management
const SearchableSimpleWithState = ({
  initialValue = '',
  options = sampleOptions,
  styles,
  ...props
}: {
  initialValue?: string
  options?: DropdownOption[]
  styles?: any
  label: string
  [key: string]: any
}) => {
  const handleChange = (option: DropdownOption | null) => {
    // Handle change if needed for demo purposes
    console.log('Selected option:', option)
  }

  return (
    <SearchableSimple
      {...props}
      options={options}
      defaultValue={initialValue}
      onChange={handleChange}
      styles={styles}
    />
  )
}

// --------------------------------------------------------------------------
// STORYBOOK METADATA
// --------------------------------------------------------------------------
const meta: Meta<typeof SearchableSimple> = {
  title: 'Components/Field/Dropdown/SearchableSimple',
  component: SearchableSimple,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    defaultValue: { control: 'text' },
    onChange: { action: 'changed' },
    label: { control: 'text' },
    placeholder: { control: 'text' },
    helperText: { control: 'text' },
    options: { control: 'object' },
    styles: { control: 'object' },
  },
  decorators: [
    Story => (
      <div style={{ width: '400px', padding: '2rem' }}>
        <Story />
      </div>
    ),
  ],
}

export default meta
type Story = StoryObj<typeof SearchableSimple>

// --------------------------------------------------------------------------
// BASIC THEME STORIES
// --------------------------------------------------------------------------

export const LightTheme: Story = {
  name: 'Light Theme (Default)',
  render: () => (
    <SearchableSimpleWithState
      label="Select Fruit"
      placeholder="Search and choose a fruit"
      styles={{ theme: 'light' }}
    />
  ),
}

export const DarkTheme: Story = {
  name: 'Dark Theme',
  render: () => (
    <SearchableSimpleWithState
      label="Select Country"
      placeholder="Search and choose a country"
      options={countryOptions}
      styles={{ theme: 'dark' }}
    />
  ),
  parameters: {
    backgrounds: { default: 'dark' },
  },
}

export const SacredTheme: Story = {
  name: 'Sacred Theme',
  render: () => (
    <SearchableSimpleWithState
      label="Divine Selection"
      placeholder="Search sacred option..."
      styles={{ theme: 'sacred' }}
    />
  ),
  parameters: {
    backgrounds: { default: 'dark' },
  },
}

// --------------------------------------------------------------------------
// CUSTOM COLOR STORIES
// --------------------------------------------------------------------------

export const CustomColors: Story = {
  name: 'Custom Colors',
  render: () => (
    <SearchableSimpleWithState
      label="Custom Dropdown"
      placeholder="Search option"
      styles={{
        theme: 'light',
        backgroundColor: 'rgba(249, 250, 251, 0.95)',
        borderColor: 'rgba(79, 70, 229, 0.4)',
        borderFocusedColor: 'rgba(79, 70, 229, 1)',
        textColor: 'rgba(55, 48, 163, 1)',
        labelColor: 'rgba(55, 48, 163, 0.7)',
      }}
    />
  ),
}

export const NeonStyle: Story = {
  name: 'Neon Style',
  render: () => (
    <SearchableSimpleWithState
      label="Neon Dropdown"
      placeholder="Search option"
      styles={{
        theme: 'dark',
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        borderColor: 'rgba(16, 185, 129, 0.5)',
        borderFocusedColor: 'rgba(16, 185, 129, 1)',
        textColor: 'rgba(16, 185, 129, 1)',
        labelColor: 'rgba(16, 185, 129, 0.7)',
        borderRadius: '12px',
        borderWidth: '2px',
      }}
    />
  ),
  parameters: {
    backgrounds: { default: 'dark' },
  },
}

// --------------------------------------------------------------------------
// LAYOUT AND SPACING STORIES
// --------------------------------------------------------------------------

export const CustomLayout: Story = {
  name: 'Custom Layout & Spacing',
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <SearchableSimpleWithState
        label="Large Padding"
        placeholder="Search option"
        styles={{
          theme: 'light',
          padding: '24px',
          borderRadius: '16px',
          fontSize: '18px',
        }}
      />
      <SearchableSimpleWithState
        label="Custom Dimensions"
        placeholder="Default height"
        styles={{
          theme: 'light',
          width: '100%',
        }}
      />
      <SearchableSimpleWithState
        label="Asymmetric Padding"
        placeholder="Different padding sides"
        styles={{
          theme: 'light',
          paddingLeft: '32px',
          paddingRight: '16px',
          paddingTop: '20px',
          paddingBottom: '20px',
        }}
      />
    </div>
  ),
}

// --------------------------------------------------------------------------
// TYPOGRAPHY STORIES
// --------------------------------------------------------------------------

export const CustomTypography: Story = {
  name: 'Custom Typography',
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <SearchableSimpleWithState
        label="Large Text"
        placeholder="Search option"
        styles={{
          theme: 'light',
          fontSize: '20px',
          fontWeight: 'bold',
          lineHeight: '1.5',
          padding: '20px',
        }}
      />
      <SearchableSimpleWithState
        label="Custom Font"
        placeholder="Different font family"
        styles={{
          theme: 'light',
          fontFamily: '"Georgia", serif',
          fontSize: '16px',
          fontWeight: 400,
        }}
      />
      <SearchableSimpleWithState
        label="Small & Light"
        placeholder="Search option"
        styles={{
          theme: 'light',
          fontSize: '14px',
          fontWeight: 300,
          padding: '12px',
        }}
      />
    </div>
  ),
}

// --------------------------------------------------------------------------
// OPTION VARIATIONS
// --------------------------------------------------------------------------

export const OptionVariations: Story = {
  name: 'Option Variations',
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <SearchableSimpleWithState
        label="Fruits"
        placeholder="Search a fruit"
        options={sampleOptions}
        styles={{ theme: 'light' }}
      />
      <SearchableSimpleWithState
        label="Countries"
        placeholder="Search a country"
        options={countryOptions}
        styles={{ theme: 'light' }}
      />
      <SearchableSimpleWithState
        label="Large Dataset"
        placeholder="Search option"
        options={Array.from({ length: 100 }, (_, i) => ({
          value: `option-${i}`,
        }))}
        styles={{ theme: 'light' }}
      />
    </div>
  ),
}

// --------------------------------------------------------------------------
// ERROR STATES
// --------------------------------------------------------------------------

export const ErrorStates: Story = {
  name: 'Error States',
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <SearchableSimpleWithState
        label="Select Option"
        placeholder="Search an option"
        error="Please select a valid option."
        styles={{ theme: 'light' }}
      />
      <SearchableSimpleWithState
        label="Country Selection"
        placeholder="Search a country"
        error="Country selection is required."
        options={countryOptions}
        styles={{
          theme: 'dark',
          borderErrorColor: 'rgba(255, 99, 71, 1)',
          labelErrorColor: 'rgba(255, 99, 71, 1)',
          footerTextErrorColor: 'rgba(255, 99, 71, 1)',
        }}
      />
      <SearchableSimpleWithState
        label="Sacred Choice"
        placeholder="Search sacred option"
        error="The divine choice is required."
        styles={{ theme: 'sacred' }}
      />
    </div>
  ),
}

// --------------------------------------------------------------------------
// REQUIRED FIELDS
// --------------------------------------------------------------------------

export const RequiredFields: Story = {
  name: 'Required Fields',
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <SearchableSimpleWithState
        label="Required Selection"
        placeholder="Search an option"
        required
        styles={{ theme: 'light' }}
      />
      <SearchableSimpleWithState
        label="Country"
        placeholder="Search a country"
        required
        error="This field is required"
        options={countryOptions}
        styles={{ theme: 'light' }}
      />
      <SearchableSimpleWithState
        label="Category"
        placeholder="Search a category"
        required
        styles={{ theme: 'dark' }}
      />
      <SearchableSimpleWithState
        label="Custom Required Dropdown"
        placeholder="Search divine option"
        required
        styles={{
          theme: 'sacred',
          requiredIndicatorText: ' (required)',
          requiredIndicatorColor: 'rgba(255, 215, 0, 1)',
        }}
      />
    </div>
  ),
}

// --------------------------------------------------------------------------
// DISABLED STATE
// --------------------------------------------------------------------------

export const DisabledStates: Story = {
  name: 'Disabled States',
  render: () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
      <SearchableSimpleWithState
        label="Disabled Light"
        initialValue="apple"
        disabled
        styles={{ theme: 'light' }}
      />
      <SearchableSimpleWithState
        label="Disabled Dark"
        initialValue="us"
        options={countryOptions}
        disabled
        styles={{ theme: 'dark' }}
      />
      <SearchableSimpleWithState
        label="Disabled Sacred"
        initialValue="banana"
        disabled
        styles={{ theme: 'sacred' }}
      />
    </div>
  ),
}

// --------------------------------------------------------------------------
// SEARCH DEMO
// --------------------------------------------------------------------------

const SearchableSimpleDemo = () => {
  const [selectedCountry, setSelectedCountry] = useState('')
  const [selectedFruit, setSelectedFruit] = useState('')
  const [error, setError] = useState('')

  const handleCountryChange = (option: DropdownOption | null) => {
    setSelectedCountry(option?.value || '')
  }

  const handleFruitChange = (option: DropdownOption | null) => {
    setSelectedFruit(option?.value || '')
  }

  const handleSubmit = () => {
    if (!selectedCountry || !selectedFruit) {
      setError('Please select both country and fruit')
    } else {
      setError('')
      alert(`Selected: ${selectedCountry} and ${selectedFruit}`)
    }
  }

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        gap: '1rem',
        width: '400px',
      }}
    >
      <h3 style={{ margin: '0 0 1rem 0' }}>Simple Searchable Dropdown Demo</h3>
      <SearchableSimple
        label="Country"
        placeholder="Search and select country"
        options={countryOptions}
        defaultValue={selectedCountry}
        onChange={handleCountryChange}
        styles={{ theme: 'light' }}
      />
      <SearchableSimple
        label="Fruit"
        placeholder="Search and select fruit"
        options={sampleOptions}
        defaultValue={selectedFruit}
        onChange={handleFruitChange}
        styles={{ theme: 'light' }}
      />
      {error && (
        <div style={{ color: 'rgba(239, 68, 68, 1)', fontSize: '14px' }}>
          {error}
        </div>
      )}
      <button
        onClick={handleSubmit}
        style={{
          padding: '12px 24px',
          backgroundColor: '#3B82F6',
          color: 'white',
          border: 'none',
          borderRadius: '8px',
          cursor: 'pointer',
          fontSize: '16px',
          fontWeight: '500',
        }}
      >
        Submit Selection
      </button>
      <div style={{ fontSize: '14px', color: '#6B7280' }}>
        <p>Simple searchable dropdown features:</p>
        <ul style={{ margin: '0.5rem 0', paddingLeft: '1.5rem' }}>
          <li>Type to search and filter options</li>
          <li>Select from filtered results</li>
          <li>Clean, simple interface</li>
          <li>No history tracking</li>
        </ul>
      </div>
    </div>
  )
}

export const SearchDemo: Story = {
  name: 'Search Demo',
  render: () => <SearchableSimpleDemo />,
}

// --------------------------------------------------------------------------
// COMPREHENSIVE SHOWCASE
// --------------------------------------------------------------------------

export const ComprehensiveShowcase: Story = {
  name: 'Comprehensive Showcase',
  render: () => (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
        gap: '2rem',
        padding: '1rem',
      }}
    >
      {/* Light Theme Section */}
      <div>
        <h3 style={{ margin: '0 0 1rem 0', color: '#374151' }}>Light Theme</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          <SearchableSimpleWithState
            label="Basic Dropdown"
            placeholder="Search option"
            styles={{ theme: 'light' }}
          />
          <SearchableSimpleWithState
            label="With Error"
            placeholder="Search option"
            error="Invalid selection"
            styles={{ theme: 'light' }}
          />
          <SearchableSimpleWithState
            label="Required Field"
            placeholder="Search option"
            required
            styles={{ theme: 'light' }}
          />
        </div>
      </div>

      {/* Dark Theme Section */}
      <div>
        <h3 style={{ margin: '0 0 1rem 0', color: '#9CA3AF' }}>Dark Theme</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          <SearchableSimpleWithState
            label="Basic Dark"
            placeholder="Search option"
            styles={{ theme: 'dark' }}
          />
          <SearchableSimpleWithState
            label="Custom Colors"
            placeholder="Custom styling"
            styles={{
              theme: 'dark',
              borderFocusedColor: 'rgba(34, 197, 94, 1)',
              labelColor: 'rgba(34, 197, 94, 0.8)',
            }}
          />
          <SearchableSimpleWithState
            label="Large Size"
            placeholder="Search option"
            styles={{
              theme: 'dark',
              fontSize: '18px',
              padding: '20px',
              borderRadius: '12px',
            }}
          />
        </div>
      </div>

      {/* Sacred Theme Section */}
      <div>
        <h3 style={{ margin: '0 0 1rem 0', color: '#FFD700' }}>Sacred Theme</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          <SearchableSimpleWithState
            label="Divine Selection"
            placeholder="Search sacred choice"
            styles={{ theme: 'sacred' }}
          />
          <SearchableSimpleWithState
            label="Sacred Dropdown"
            placeholder="Search divine option"
            error="Choice forbidden"
            styles={{ theme: 'sacred' }}
          />
          <SearchableSimpleWithState
            label="Holy Selection"
            placeholder="Search divine choice"
            styles={{
              theme: 'sacred',
              borderRadius: '16px',
              padding: '18px',
            }}
          />
        </div>
      </div>

      {/* Custom Styling Section */}
      <div>
        <h3 style={{ margin: '0 0 1rem 0', color: '#7C3AED' }}>
          Custom Styling
        </h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          <SearchableSimpleWithState
            label="Neon Style"
            placeholder="Search option"
            styles={{
              theme: 'dark',
              backgroundColor: 'rgba(0, 0, 0, 0.95)',
              borderColor: 'rgba(147, 51, 234, 0.5)',
              borderFocusedColor: 'rgba(147, 51, 234, 1)',
              textColor: 'rgba(147, 51, 234, 1)',
              labelColor: 'rgba(147, 51, 234, 0.8)',
              borderRadius: '20px',
              borderWidth: '2px',
            }}
          />
          <SearchableSimpleWithState
            label="Soft Rounded"
            placeholder="Search option"
            styles={{
              theme: 'light',
              backgroundColor: 'rgba(249, 250, 251, 1)',
              borderColor: 'rgba(209, 213, 219, 1)',
              borderFocusedColor: 'rgba(59, 130, 246, 1)',
              borderRadius: '24px',
              padding: '16px 24px',
            }}
          />
          <SearchableSimpleWithState
            label="Minimal"
            placeholder="Search option"
            styles={{
              theme: 'light',
              backgroundColor: 'rgba(255, 255, 255, 1)',
              borderColor: 'rgba(0, 0, 0, 0.1)',
              borderFocusedColor: 'rgba(0, 0, 0, 0.3)',
              borderRadius: '0px',
              borderWidth: '0px 0px 2px 0px',
              padding: '12px 0px',
            }}
          />
        </div>
      </div>
    </div>
  ),
  parameters: {
    layout: 'fullscreen',
    backgrounds: { default: 'light' },
  },
}

// --------------------------------------------------------------------------
// INTERACTION TEST
// --------------------------------------------------------------------------

export const InteractionTest: Story = {
  name: 'Interaction Test',
  render: () => (
    <SearchableSimpleWithState
      label="Test Searchable Simple"
      placeholder="Search and select..."
      styles={{ theme: 'light' }}
    />
  ),
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement)
    const label = canvas.getByText('Test Searchable Simple')
    const dropdown = canvas.getByRole('button')

    // Initial state
    expect(label).toBeVisible()
    expect(dropdown).toBeVisible()

    // Click to open dropdown
    await userEvent.click(dropdown)

    // The dropdown should be interactive
    expect(dropdown).toBeVisible()
  },
}
