import { useState } from 'react';
import { Filtros, getFiltrosHasActiveFilters } from './Filtros';

const baseOptions = {
  tipo: [
    { value: 'all', label: 'Todos' },
    { value: 'recibos', label: 'Recibos' },
    { value: 'contratos', label: 'Contratos' },
    { value: 'certificados', label: 'Certificados' },
    { value: 'otros', label: 'Otros' },
  ],
  estado: [
    { value: 'all', label: 'Todos' },
    { value: 'active', label: 'Activo' },
    { value: 'pending', label: 'Pendiente' },
    { value: 'expired', label: 'Vencido' },
  ],
  periodo: [
    { value: 'all', label: 'Todos' },
    { value: '7', label: '7 dias' },
    { value: '30', label: '30 dias' },
    { value: '90', label: '90 dias' },
  ],
};

export default {
  title: 'Layout/Filtros',
  component: Filtros,
  parameters: {
    layout: 'padded',
    viewport: {
      viewports: {
        filtrosIntermedio: {
          name: 'Filtros intermedio (1200px)',
          styles: { width: '1200px', height: '800px' },
        },
      },
    },
  },
  args: {
    filterByLabel: 'Filtrar por:',
    importationLabel: 'Importacion',
    dateFromPlaceholder: 'Desde',
    dateToPlaceholder: 'Hasta',
    mobileBreakpoint: 1024,
    intermediateBreakpointMax: 1439,
    mobileButtonLabel: 'Filtros',
    mobileButtonBackgroundColor: '#FFFFFF',
    mobileButtonBorderColor: '#38656D',
    mobileButtonTextColor: '#38656D',
    mobileButtonIconName: 'AdjustmentsHorizontalIcon',
    mobileButtonIconVariant: '24-outline',
    mobileButtonIconSize: 18,
    mobileButtonIconColor: '#38656D',
    mobileButtonCount: undefined,
    mobileTitle: 'Filtros',
    mobileTitleColor: '#2D4952',
    mobileTitleFontSize: '24px',
    mobileTitleLineHeight: '30px',
    mobileTitleFontWeight: 400,
    applyButtonLabel: 'Filtrar',
    applyButtonBackgroundColor: '#3F7680',
    applyButtonTextColor: '#FFFFFF',
    cancelButtonLabel: 'Cancelar',
    cancelButtonBackgroundColor: '#FFFFFF',
    cancelButtonBorderColor: '#5E8691',
    cancelButtonTextColor: '#2D4952',
    activeColor: '#6D3856',
    panelBackground: '#FFFFFF',
  },
};

const StatefulTemplate = (args) => {
  const [tipo, setTipo] = useState('all');
  const [estado, setEstado] = useState('all');
  const [periodo, setPeriodo] = useState('all');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');

  const handleClearFilters = () => {
    setTipo('all');
    setEstado('all');
    setPeriodo('all');
    setDateFrom('');
    setDateTo('');
  };

  const items = [
    {
      id: 'tipo',
      label: 'Tipo',
      value: tipo,
      options: baseOptions.tipo,
      onChange: (nextValue) => setTipo(nextValue),
    },
    {
      id: 'estado',
      label: 'Estado',
      value: estado,
      options: baseOptions.estado,
      onChange: (nextValue) => setEstado(nextValue),
    },
    {
      id: 'periodo',
      label: 'Periodo',
      value: periodo,
      options: baseOptions.periodo,
      onChange: (nextValue) => setPeriodo(nextValue),
    },
  ];

  const hasActiveFilters = getFiltrosHasActiveFilters({
    items,
    dateFromValue: dateFrom,
    dateToValue: dateTo,
  });

  return (
    <div>
      <Filtros
        {...args}
        items={items}
        dateFromValue={dateFrom}
        dateToValue={dateTo}
        onDateFromChange={setDateFrom}
        onDateToChange={setDateTo}
        hasActiveFilters={hasActiveFilters}
        onClearFilters={handleClearFilters}
        onApply={() => {
          // Placeholder de historia para mostrar el callback de consumo.
          console.log('Aplicar filtros', { tipo, estado, periodo, dateFrom, dateTo });
        }}
      />
    </div>
  );
};

export const DesktopYMobile = {
  render: StatefulTemplate,
};

/** 1025–1439 px: filtros en fila 1, importación en fila 2. */
export const LayoutIntermedio = {
  render: StatefulTemplate,
  parameters: {
    viewport: {
      defaultViewport: 'filtrosIntermedio',
    },
    docs: {
      description: {
        story:
          'Viewport entre mobileBreakpoint (1024) e intermediateBreakpointMax (1439): dropdowns arriba, fechas de importación abajo.',
      },
    },
  },
};

export const MobileForzado = {
  render: StatefulTemplate,
  args: {
    mobileBreakpoint: 9999,
  },
};

export const MobileControladoPorHost = {
  render: (args) => {
    const [tipo, setTipo] = useState('all');
    const [estado, setEstado] = useState('all');
    const [periodo, setPeriodo] = useState('all');
    const [dateFrom, setDateFrom] = useState('');
    const [dateTo, setDateTo] = useState('');
    const [isOpen, setIsOpen] = useState(false);

    const items = [
      {
        id: 'tipo',
        label: 'Tipo',
        value: tipo,
        options: baseOptions.tipo,
        onChange: (nextValue) => setTipo(nextValue),
      },
      {
        id: 'estado',
        label: 'Estado',
        value: estado,
        options: baseOptions.estado,
        onChange: (nextValue) => setEstado(nextValue),
      },
      {
        id: 'periodo',
        label: 'Periodo',
        value: periodo,
        options: baseOptions.periodo,
        onChange: (nextValue) => setPeriodo(nextValue),
      },
    ];

    const hasActiveFilters = getFiltrosHasActiveFilters({
      items,
      dateFromValue: dateFrom,
      dateToValue: dateTo,
    });

    const handleClearFilters = () => {
      setTipo('all');
      setEstado('all');
      setPeriodo('all');
      setDateFrom('');
      setDateTo('');
    };

    return (
      <div>
        <button
          type="button"
          onClick={() => setIsOpen((prev) => !prev)}
          style={{
            marginBottom: '12px',
            padding: '8px 12px',
            borderRadius: '8px',
            border: '1px solid #5E8691',
          }}
        >
          Toggle externo panel mobile
        </button>

        <Filtros
          {...args}
          items={items}
          dateFromValue={dateFrom}
          dateToValue={dateTo}
          onDateFromChange={setDateFrom}
          onDateToChange={setDateTo}
          hasActiveFilters={hasActiveFilters}
          onClearFilters={handleClearFilters}
          mobileBreakpoint={9999}
          isMobilePanelOpen={isOpen}
          onMobilePanelOpenChange={setIsOpen}
        />
      </div>
    );
  },
};
