import React, { useState } from 'react';
import styled, { css } from 'styled-components';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Input, Spinner } from '@/shared/components/ui';
import type { QuickFilter, SavedFilter } from '@/features/search/types/search.types';

const Wrap = styled.div<{ $variant: 'inline' | 'rail' }>`
  display: flex;
  flex-direction: column;
  gap: ${({ theme, $variant }) => ($variant === 'rail' ? theme.spacing[5] : theme.spacing[5])};
  margin: 0;
  padding: 0;

  ${({ $variant, theme }) =>
    $variant === 'inline' &&
    css`
      padding-bottom: ${theme.spacing[5]};
      border-bottom: 1px solid ${theme.colors.borderSoft};
    `}
`;

const Block = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[3]};
`;

const SectionTitle = styled.h2`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.widest};
  text-transform: uppercase;
  color: ${({ theme }) => theme.colors.text.tertiary};
  margin: 0;
  text-align: start;
`;

const Row = styled.div<{ $rail?: boolean }>`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
  align-items: center;

  ${({ $rail }) =>
    $rail &&
    css`
      flex-direction: column;
      align-items: stretch;
    `}
`;

const Chip = styled.button<{ $active?: boolean; $rail?: boolean }>`
  border: 1px solid
    ${({ theme, $active }) => ($active ? theme.colors.primary : theme.colors.borderSoft)};
  background: ${({ theme, $active }) =>
    $active ? theme.colors.primaryLight : theme.colors.surfaceElevated};
  color: ${({ theme, $active }) =>
    $active ? theme.colors.primaryDark : theme.colors.text.secondary};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  padding: ${({ theme }) => `${theme.spacing[2]} ${theme.spacing[3]}`};
  min-height: 36px;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  cursor: pointer;
  text-align: start;
  box-shadow: ${({ theme, $active }) => ($active ? theme.shadows.sm : 'none')};
  transition:
    background ${({ theme }) => theme.transitions.fast},
    border-color ${({ theme }) => theme.transitions.fast},
    box-shadow ${({ theme }) => theme.transitions.fast};

  ${({ $rail }) =>
    $rail &&
    css`
      width: 100%;
    `}

  &:hover {
    border-color: ${({ theme }) => theme.colors.primary};
  }
`;

const SaveRow = styled.div<{ $rail?: boolean }>`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
  align-items: flex-end;
  margin-top: ${({ theme }) => theme.spacing[1]};

  ${({ $rail }) =>
    $rail &&
    css`
      flex-direction: column;
      align-items: stretch;
    `}
`;

const SavedRow = styled.div<{ $rail?: boolean }>`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[2]};
  align-items: center;
  width: 100%;

  ${({ $rail }) =>
    $rail &&
    css`
      flex-direction: column;
      align-items: stretch;
    `}
`;

const Message = styled.div`
  margin: 0;
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  text-align: start;
`;

interface SavedFiltersBarProps {
  variant?: 'inline' | 'rail';
  personal: SavedFilter[];
  shared: SavedFilter[];
  quick: QuickFilter[];
  activeQuickId?: string | null;
  activeSavedId?: string | null;
  isLoading?: boolean;
  isError?: boolean;
  isSaving?: boolean;
  onQuickSelect: (quick: QuickFilter) => void;
  onSavedSelect: (filter: SavedFilter) => void;
  onSaveCurrent: (name: string) => void;
  onDeleteSaved: (filterId: string) => void;
}

export const SavedFiltersBar: React.FC<SavedFiltersBarProps> = ({
  variant = 'inline',
  personal,
  shared,
  quick,
  activeQuickId,
  activeSavedId,
  isLoading,
  isError,
  isSaving,
  onQuickSelect,
  onSavedSelect,
  onSaveCurrent,
  onDeleteSaved,
}) => {
  const { t } = useLocale();
  const [saveName, setSaveName] = useState('');

  const handleSave = () => {
    const trimmed = saveName.trim();
    if (!trimmed) return;
    onSaveCurrent(trimmed);
    setSaveName('');
  };

  const isRail = variant === 'rail';

  return (
    <Wrap $variant={variant}>
      <Block>
        <SectionTitle>{t('search:quick.title')}</SectionTitle>
        {isLoading ? (
          <Message>
            <Spinner size="sm" />
            {t('search:saved.loading')}
          </Message>
        ) : isError ? (
          <Message>{t('search:saved.error')}</Message>
        ) : (
          <Row $rail={isRail}>
            {quick.map((item) => (
              <Chip
                key={item.id}
                type="button"
                $rail={isRail}
                $active={activeQuickId === item.id}
                onClick={() => onQuickSelect(item)}
              >
                {item.name}
              </Chip>
            ))}
          </Row>
        )}
      </Block>

      <Block>
        <SectionTitle>{t('search:saved.title')}</SectionTitle>
        {(personal.length > 0 || shared.length > 0) && (
          <>
            {personal.length > 0 && (
              <Row $rail={isRail}>
                {personal.map((filter) => (
                  <SavedRow key={filter.id} $rail={isRail}>
                    <Chip
                      type="button"
                      $rail={isRail}
                      $active={activeSavedId === filter.id}
                      onClick={() => onSavedSelect(filter)}
                    >
                      {filter.name}
                    </Chip>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onDeleteSaved(filter.id)}
                    >
                      {t('search:saved.delete')}
                    </Button>
                  </SavedRow>
                ))}
              </Row>
            )}
            {shared.length > 0 && (
              <Row $rail={isRail}>
                {shared.map((filter) => (
                  <Chip
                    key={filter.id}
                    type="button"
                    $rail={isRail}
                    $active={activeSavedId === filter.id}
                    onClick={() => onSavedSelect(filter)}
                  >
                    {filter.name}
                  </Chip>
                ))}
              </Row>
            )}
          </>
        )}
        <SaveRow $rail={isRail}>
          <Input
            label={t('search:saved.saveLabel')}
            value={saveName}
            onChange={(event) => setSaveName(event.target.value)}
            placeholder={t('search:saved.savePlaceholder')}
            fullWidth
          />
          <Button variant="secondary" loading={isSaving} disabled={!saveName.trim()} onClick={handleSave}>
            {t('search:saved.save')}
          </Button>
        </SaveRow>
      </Block>
    </Wrap>
  );
};
