'use client';

import { useMemo } from 'react';
import Link from 'next/link';
import { parseAsString, useQueryStates } from 'nuqs';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { CrmDateInput } from '@/features/crm/components/crm-form-controls';
import type { CrmReportFilterMetadata } from '../api/types';

type FilterKey =
  | 'dateFrom'
  | 'dateTo'
  | 'branch'
  | 'productType'
  | 'sales'
  | 'customerOwner'
  | 'leadSource';

const FILTER_LABELS: Record<Exclude<FilterKey, 'dateFrom' | 'dateTo'>, string> = {
  branch: 'Branch',
  productType: 'Product Type',
  sales: 'Salesman',
  customerOwner: 'Customer Owner',
  leadSource: 'Lead Source'
};

export function ReportFilterBar({
  filterMetadata,
  filterKeys,
  canExport,
  reportCode,
  pageLinks
}: {
  filterMetadata: CrmReportFilterMetadata;
  filterKeys: FilterKey[];
  canExport: boolean;
  reportCode?: string;
  pageLinks?: Array<{ href: string; label: string; active?: boolean }>;
}) {
  const [params, setParams] = useQueryStates({
    dateFrom: parseAsString,
    dateTo: parseAsString,
    branch: parseAsString,
    productType: parseAsString,
    sales: parseAsString,
    customerOwner: parseAsString,
    leadSource: parseAsString
  });

  const exportQuery = useMemo(() => {
    const searchParams = new URLSearchParams();

    if (params.dateFrom) searchParams.set('dateFrom', params.dateFrom);
    if (params.dateTo) searchParams.set('dateTo', params.dateTo);
    if (params.branch) searchParams.set('branch', params.branch);
    if (params.productType) searchParams.set('productType', params.productType);
    if (params.sales) searchParams.set('sales', params.sales);
    if (params.customerOwner) searchParams.set('customerOwner', params.customerOwner);
    if (params.leadSource) searchParams.set('leadSource', params.leadSource);
    if (reportCode) searchParams.set('reportCode', reportCode);

    return searchParams.toString();
  }, [params, reportCode]);

  const optionMap = {
    branch: filterMetadata.branches.map((item) => ({ value: item.id, label: item.label })),
    productType: filterMetadata.productTypes.map((item) => ({ value: item.id, label: item.label })),
    sales: filterMetadata.sales.map((item) => ({ value: item.id, label: item.name })),
    customerOwner: filterMetadata.customerOwners.map((item) => ({ value: item.id, label: item.name })),
    leadSource: filterMetadata.leadSources.map((item) => ({ value: item.id, label: item.label }))
  } as const;

  return (
    <div className='space-y-3 rounded-xl border bg-card p-4'>
      {pageLinks?.length ? (
        <div className='flex flex-wrap gap-2'>
          {pageLinks.map((link) => (
            <Button key={link.href} asChild variant={link.active ? 'default' : 'outline'} size='sm'>
              <Link href={link.href}>{link.label}</Link>
            </Button>
          ))}
        </div>
      ) : null}

      <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-6'>
        {filterKeys.includes('dateFrom') ? (
          <CrmDateInput
            value={params.dateFrom ?? ''}
            onChange={(value) => void setParams({ dateFrom: value || null })}
          />
        ) : null}
        {filterKeys.includes('dateTo') ? (
          <CrmDateInput
            value={params.dateTo ?? ''}
            onChange={(value) => void setParams({ dateTo: value || null })}
          />
        ) : null}
        {(
          ['branch', 'productType', 'sales', 'customerOwner', 'leadSource'] as const
        ).filter((key) => filterKeys.includes(key)).map((key) => (
          <Select
            key={key}
            value={params[key] ?? '__all__'}
            onValueChange={(value) => void setParams({ [key]: value === '__all__' ? null : value })}
          >
            <SelectTrigger>
              <SelectValue placeholder={FILTER_LABELS[key]} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value='__all__'>All {FILTER_LABELS[key]}</SelectItem>
              {optionMap[key].map((item) => (
                <SelectItem key={item.value} value={item.value}>
                  {item.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ))}
      </div>

      <div className='flex flex-wrap items-center gap-2'>
        <Button
          variant='outline'
          onClick={() =>
            void setParams({
              dateFrom: null,
              dateTo: null,
              branch: null,
              productType: null,
              sales: null,
              customerOwner: null,
              leadSource: null
            })
          }
        >
          Clear Filters
        </Button>
        {canExport && reportCode ? (
          <>
            <Button asChild variant='outline'>
              <Link href={`/api/crm/reports/export?format=csv${exportQuery ? `&${exportQuery}` : ''}`}>
                <Icons.download className='mr-2 h-4 w-4' />
                Export CSV
              </Link>
            </Button>
            <Button asChild variant='outline'>
              <Link href={`/api/crm/reports/export?format=xls${exportQuery ? `&${exportQuery}` : ''}`}>
                <Icons.download className='mr-2 h-4 w-4' />
                Export Excel
              </Link>
            </Button>
          </>
        ) : null}
      </div>
    </div>
  );
}
