import React from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import { SearchBar } from './SearchBar';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';

const meta: Meta<typeof SearchBar> = {
  title: 'Molecules/SearchBar',
  component: SearchBar,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
  },
  argTypes: {
    value: { control: 'text' },
    placeholder: { control: 'text' },
    size: { control: 'select', options: ['medium', 'small'] },
    showButton: { control: 'boolean' },
    buttonLabel: { control: 'text' },
    disabled: { control: 'boolean' },
    loading: { control: 'boolean' },
    fullWidth: { control: 'boolean' },
  },
  decorators: [
    (Story) => (
      <Box sx={{ width: 480 }}>
        <Story />
      </Box>
    ),
  ],
};

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

// ─── Default ────────────────────────────────────────────────────────────────

/** Default — input-only search bar with Enter to submit */
export const Default: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('');
    const [submitted, setSubmitted] = React.useState('');

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <SearchBar
          value={value}
          onChange={setValue}
          onSearch={setSubmitted}
          placeholder="Search funeral directors..."
        />
        {submitted && (
          <Typography variant="body2" color="text.secondary">
            Searched for: &ldquo;{submitted}&rdquo;
          </Typography>
        )}
      </Box>
    );
  },
};

// ─── With Button ────────────────────────────────────────────────────────────

/** Search bar with an explicit submit button */
export const WithButton: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('');
    const [submitted, setSubmitted] = React.useState('');

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <SearchBar
          value={value}
          onChange={setValue}
          onSearch={setSubmitted}
          placeholder="Search venues..."
          showButton
        />
        {submitted && (
          <Typography variant="body2" color="text.secondary">
            Searched for: &ldquo;{submitted}&rdquo;
          </Typography>
        )}
      </Box>
    );
  },
};

// ─── Small Size ─────────────────────────────────────────────────────────────

/** Small size (40px) — for compact layouts like sidebar filters */
export const SmallSize: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('');

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        <Box>
          <Typography variant="label" sx={{ mb: 1, display: 'block' }}>
            Medium (48px) — default
          </Typography>
          <SearchBar
            value={value}
            onChange={setValue}
            placeholder="Search providers..."
            showButton
          />
        </Box>
        <Box>
          <Typography variant="label" sx={{ mb: 1, display: 'block' }}>
            Small (40px) — compact
          </Typography>
          <SearchBar
            value={value}
            onChange={setValue}
            placeholder="Search providers..."
            size="small"
            showButton
          />
        </Box>
      </Box>
    );
  },
};

// ─── With Preloaded Value ───────────────────────────────────────────────────

/** Pre-filled value with clear button visible */
export const WithPreloadedValue: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('Melbourne funeral directors');

    return (
      <SearchBar
        value={value}
        onChange={setValue}
        placeholder="Search funeral directors..."
        showButton
      />
    );
  },
};

// ─── Loading State ──────────────────────────────────────────────────────────

/** Loading — search in progress, button shows spinner */
export const Loading: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('Parsons funeral');

    return (
      <SearchBar value={value} onChange={setValue} placeholder="Search..." showButton loading />
    );
  },
};

// ─── Disabled ───────────────────────────────────────────────────────────────

/** Disabled — entire search bar is non-interactive */
export const Disabled: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('');

    return (
      <SearchBar
        value={value}
        onChange={setValue}
        placeholder="Search unavailable..."
        showButton
        disabled
      />
    );
  },
};

// ─── Provider Search ────────────────────────────────────────────────────────

/** Realistic — provider search on listing page */
export const ProviderSearch: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('');
    const [results, setResults] = React.useState<string[]>([]);

    const providers = [
      'H. Parsons Funeral Directors',
      'Peaceful Rest Funerals',
      'Heritage Memorials',
      'Garden of Memories',
      'Bayside Funeral Services',
    ];

    const handleSearch = (query: string) => {
      if (!query.trim()) {
        setResults([]);
        return;
      }
      setResults(providers.filter((p) => p.toLowerCase().includes(query.toLowerCase())));
    };

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <Typography variant="h5">Find a funeral director</Typography>
        <SearchBar
          value={value}
          onChange={(v) => {
            setValue(v);
            handleSearch(v);
          }}
          onSearch={handleSearch}
          placeholder="Search by name or suburb..."
          showButton
          buttonLabel="Find"
        />
        {results.length > 0 && (
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            {results.map((name) => (
              <Typography key={name} variant="body2">
                {name}
              </Typography>
            ))}
          </Box>
        )}
        {value && results.length === 0 && (
          <Typography variant="body2" color="text.secondary">
            No providers match &ldquo;{value}&rdquo;
          </Typography>
        )}
      </Box>
    );
  },
};

// ─── Venue Search ───────────────────────────────────────────────────────────

/** Realistic — venue search with compact size */
export const VenueSearch: Story = {
  render: function Render() {
    const [value, setValue] = React.useState('');

    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <Typography variant="h5">Find a venue</Typography>
        <Typography variant="body2" color="text.secondary">
          Search chapels, gardens, churches, and function venues near you.
        </Typography>
        <SearchBar
          value={value}
          onChange={setValue}
          placeholder="Suburb, postcode, or venue name..."
          size="small"
        />
      </Box>
    );
  },
};
