import React, { useMemo, useState } from 'react';
import styled from 'styled-components';
import { HiChevronDown, HiChevronUp } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Input, Select } from '@/shared/components/ui';
import { AssigneePicker } from '@/features/tickets/components/AssigneePicker';
import type { AssignableUser } from '@/features/tickets/types/ticketForm.types';
import type { SearchFilters } from '@/features/search/types/search.types';
import type { TicketPriorityRef, TicketStatusRef } from '@/features/tickets/types/ticket.types';
import { localizedName } from '@/features/tickets/utils/ticketDisplay';
import { DatePairRow, FilterGroup } from '@/features/search/components/FilterGroup';

const Panel = styled.div`
  display: grid;
  gap: ${({ theme }) => theme.spacing[6]};
  margin-top: ${({ theme }) => theme.spacing[5]};
  padding: ${({ theme }) => theme.spacing[5]} 0 0;
  border-top: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const FiltersToggle = styled.button`
  display: inline-flex;
  width: 100%;
  align-items: center;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[3]};
  padding: ${({ theme }) => `${theme.spacing[3]} ${theme.spacing[4]}`};
  border: 1px solid ${({ theme }) => theme.colors.border};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  background: ${({ theme }) => theme.colors.surface};
  color: ${({ theme }) => theme.colors.text.primary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  cursor: pointer;
  transition: background-color ${({ theme }) => theme.transitions.fast};

  &:hover {
    background: ${({ theme }) => theme.colors.surfaceMuted};
  }

  &:focus-visible {
    outline: 2px solid ${({ theme }) => theme.colors.primary};
    outline-offset: 2px;
  }
`;

const PanelBody = styled.div<{ $open: boolean }>`
  display: ${({ $open }) => ($open ? 'grid' : 'none')};
  gap: ${({ theme }) => theme.spacing[6]};
  margin-top: ${({ theme }) => theme.spacing[4]};
`;

const CheckboxGrid = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[5]} ${({ theme }) => theme.spacing[6]};
  grid-column: 1 / -1;
`;

const CheckboxLabel = styled.label`
  display: inline-flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  min-height: 40px;
  padding: ${({ theme }) => `${theme.spacing[2]} ${theme.spacing[4]}`};
  border-radius: ${({ theme }) => theme.borderRadius.lg};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.secondary};
  background: ${({ theme }) => theme.colors.surfaceInset};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  cursor: pointer;
  transition: background-color ${({ theme }) => theme.transitions.fast};

  &:hover {
    background: ${({ theme }) => theme.colors.surfaceMuted};
  }

  input {
    accent-color: ${({ theme }) => theme.colors.primary};
  }
`;

const ClearRow = styled.div`
  display: flex;
  justify-content: flex-end;
  margin-top: ${({ theme }) => theme.spacing[2]};
`;

const SLA_OPTIONS = [
  { value: '', labelKey: 'all' },
  { value: 'active', labelKey: 'active' },
  { value: 'warning', labelKey: 'warning' },
  { value: 'breached', labelKey: 'breached' },
  { value: 'met', labelKey: 'met' },
  { value: 'paused', labelKey: 'paused' },
] as const;

interface SearchFiltersPanelProps {
  filters: SearchFilters;
  statuses: TicketStatusRef[];
  priorities: TicketPriorityRef[];
  categories: { id: string; name_en: string; name_ar: string }[];
  departmentId?: string;
  onChange: (patch: Partial<SearchFilters>) => void;
}

export const SearchFiltersPanel: React.FC<SearchFiltersPanelProps> = ({
  filters,
  statuses,
  priorities,
  categories,
  departmentId,
  onChange,
}) => {
  const { t, locale } = useLocale();
  const [expanded, setExpanded] = useState(false);

  const assigneeValue = useMemo((): AssignableUser | null => {
    if (!filters.assigned_to) {
      return null;
    }
    return { id: filters.assigned_to, name: filters.assigned_to, email: '' };
  }, [filters.assigned_to]);

  const requesterValue = useMemo((): AssignableUser | null => {
    if (!filters.requester_id) {
      return null;
    }
    return { id: filters.requester_id, name: filters.requester_id, email: '' };
  }, [filters.requester_id]);

  const clearAll = () => {
    onChange({
      status_ids: undefined,
      priority_ids: undefined,
      category_id: undefined,
      assigned_to: undefined,
      requester_id: undefined,
      date_from: undefined,
      date_to: undefined,
      sla_status: undefined,
      has_attachments: undefined,
      is_unassigned: undefined,
      is_replied: undefined,
    });
  };

  return (
    <Panel>
      <FiltersToggle
        type="button"
        aria-expanded={expanded}
        onClick={() => setExpanded((open) => !open)}
      >
        {t('search:filters.advancedTitle')}
        {expanded ? <HiChevronUp aria-hidden /> : <HiChevronDown aria-hidden />}
      </FiltersToggle>

      <PanelBody $open={expanded}>
        <FilterGroup title={t('search:filters.quickGroup')}>
          <Select
            label={t('search:filters.status')}
            value={filters.status_ids?.[0] ?? ''}
            onChange={(event) =>
              onChange({
                status_ids: event.target.value ? [event.target.value] : undefined,
              })
            }
            options={[
              { value: '', label: t('search:filters.all') },
              ...statuses.map((status) => ({
                value: status.id,
                label: localizedName(status, locale),
              })),
            ]}
            fullWidth
          />

          <Select
            label={t('search:filters.priority')}
            value={filters.priority_ids?.[0] ?? ''}
            onChange={(event) =>
              onChange({
                priority_ids: event.target.value ? [event.target.value] : undefined,
              })
            }
            options={[
              { value: '', label: t('search:filters.all') },
              ...priorities.map((priority) => ({
                value: priority.id,
                label: localizedName(priority, locale),
              })),
            ]}
            fullWidth
          />

          <Select
            label={t('search:filters.category')}
            value={filters.category_id ?? ''}
            onChange={(event) =>
              onChange({ category_id: event.target.value || undefined })
            }
            options={[
              { value: '', label: t('search:filters.all') },
              ...categories.map((category) => ({
                value: category.id,
                label: localizedName(category, locale),
              })),
            ]}
            fullWidth
          />

          <Select
            label={t('search:filters.slaStatus')}
            value={filters.sla_status ?? ''}
            onChange={(event) =>
              onChange({ sla_status: event.target.value || undefined })
            }
            options={SLA_OPTIONS.map((option) => ({
              value: option.value,
              label: option.value
                ? t(`search:sla.${option.labelKey}`)
                : t('search:filters.all'),
            }))}
            fullWidth
          />
        </FilterGroup>

        <FilterGroup title={t('search:filters.peopleDatesGroup')}>
          {departmentId ? (
            <>
              <AssigneePicker
                departmentId={departmentId}
                label={t('search:filters.assignee')}
                value={assigneeValue}
                onChange={(user) =>
                  onChange({ assigned_to: user?.id, is_unassigned: user ? undefined : filters.is_unassigned })
                }
              />
              <AssigneePicker
                departmentId={departmentId}
                label={t('search:filters.requester')}
                value={requesterValue}
                onChange={(user) => onChange({ requester_id: user?.id })}
              />
            </>
          ) : (
            <>
              <Input
                label={t('search:filters.assignee')}
                value={filters.assigned_to ?? ''}
                onChange={(event) =>
                  onChange({ assigned_to: event.target.value.trim() || undefined })
                }
                placeholder={t('search:filters.userIdPlaceholder')}
                fullWidth
              />
              <Input
                label={t('search:filters.requester')}
                value={filters.requester_id ?? ''}
                onChange={(event) =>
                  onChange({ requester_id: event.target.value.trim() || undefined })
                }
                placeholder={t('search:filters.userIdPlaceholder')}
                fullWidth
              />
            </>
          )}

          <DatePairRow>
            <Input
              label={t('search:filters.dateFrom')}
              type="date"
              value={filters.date_from ?? ''}
              onChange={(event) =>
                onChange({ date_from: event.target.value || undefined })
              }
              fullWidth
            />
            <Input
              label={t('search:filters.dateTo')}
              type="date"
              value={filters.date_to ?? ''}
              onChange={(event) => onChange({ date_to: event.target.value || undefined })}
              fullWidth
            />
          </DatePairRow>
        </FilterGroup>

        <FilterGroup title={t('search:filters.flagsGroup')}>
          <CheckboxGrid>
            <CheckboxLabel>
              <input
                type="checkbox"
                checked={Boolean(filters.is_unassigned)}
                onChange={(event) =>
                  onChange({
                    is_unassigned: event.target.checked || undefined,
                    assigned_to: event.target.checked ? undefined : filters.assigned_to,
                  })
                }
              />
              {t('search:filters.unassigned')}
            </CheckboxLabel>

            <CheckboxLabel>
              <input
                type="checkbox"
                checked={filters.has_attachments === true}
                onChange={(event) =>
                  onChange({
                    has_attachments: event.target.checked ? true : undefined,
                  })
                }
              />
              {t('search:filters.hasAttachments')}
            </CheckboxLabel>
          </CheckboxGrid>
        </FilterGroup>

        <ClearRow>
          <Button type="button" variant="secondary" size="sm" onClick={clearAll}>
            {t('search:filters.clear')}
          </Button>
        </ClearRow>
      </PanelBody>
    </Panel>
  );
};
