'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 { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import type { CrmDashboardReferenceData } from '../api/types';

export function DashboardFilters({
  referenceData,
  canExport
}: {
  referenceData: CrmDashboardReferenceData;
  canExport: boolean;
}) {
  const [params, setParams] = useQueryStates({
    dateFrom: parseAsString,
    dateTo: parseAsString,
    branch: parseAsString,
    salesman: parseAsString,
    projectPartyRole: parseAsString,
    productType: 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.salesman) searchParams.set('salesman', params.salesman);
    if (params.projectPartyRole) searchParams.set('projectPartyRole', params.projectPartyRole);
    if (params.productType) searchParams.set('productType', params.productType);

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

  return (
    <div className='flex flex-col gap-4 rounded-xl border bg-card p-4'>
      <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-6'>
        <Input
          type='date'
          value={params.dateFrom ?? ''}
          onChange={(event) => void setParams({ dateFrom: event.target.value || null })}
        />
        <Input
          type='date'
          value={params.dateTo ?? ''}
          onChange={(event) => void setParams({ dateTo: event.target.value || null })}
        />
        <Select
          value={params.branch ?? '__all__'}
          onValueChange={(value) => void setParams({ branch: value === '__all__' ? null : value })}
        >
            <SelectTrigger>
            <SelectValue placeholder='สาขา' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='__all__'>ทุกสาขา</SelectItem>
            {referenceData.branches.map((item) => (
              <SelectItem key={item.id} value={item.id}>
                {item.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          value={params.salesman ?? '__all__'}
          onValueChange={(value) => void setParams({ salesman: value === '__all__' ? null : value })}
        >
            <SelectTrigger>
            <SelectValue placeholder='ฝ่ายขาย' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='__all__'>ฝ่ายขายทั้งหมด</SelectItem>
            {referenceData.salesmen.map((item) => (
              <SelectItem key={item.id} value={item.id}>
                {item.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          value={params.projectPartyRole ?? '__all__'}
          onValueChange={(value) =>
            void setParams({ projectPartyRole: value === '__all__' ? null : value })
          }
        >
            <SelectTrigger>
            <SelectValue placeholder='บทบาทผู้เกี่ยวข้องในโครงการ' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='__all__'>ทุกบทบาท</SelectItem>
            {referenceData.projectPartyRoles.map((item) => (
              <SelectItem key={item.id} value={item.id}>
                {item.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          value={params.productType ?? '__all__'}
          onValueChange={(value) => void setParams({ productType: value === '__all__' ? null : value })}
        >
            <SelectTrigger>
            <SelectValue placeholder='ประเภทสินค้า' />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value='__all__'>ทุกประเภทสินค้า</SelectItem>
            {referenceData.productTypes.map((item) => (
              <SelectItem key={item.id} value={item.id}>
                {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,
              salesman: null,
              projectPartyRole: null,
              productType: null
            })
          }
        >
          ล้างตัวกรอง
        </Button>
        {canExport ? (
          <>
            <Button asChild variant='outline'>
              <Link
                href={`/api/crm/dashboard/export?section=sales-ranking&format=csv${
                  exportQuery ? `&${exportQuery}` : ''
                }`}
              >
                <Icons.download className='mr-2 h-4 w-4' /> ส่งออก CSV อันดับฝ่ายขาย
              </Link>
            </Button>
            <Button asChild variant='outline'>
              <Link
                href={`/api/crm/dashboard/export?section=revenue-analytics&format=xls${
                  exportQuery ? `&${exportQuery}` : ''
                }`}
              >
                <Icons.download className='mr-2 h-4 w-4' /> ส่งออก Excel มูลค่าใบเสนอราคา
              </Link>
            </Button>
            <Button asChild variant='outline'>
              <Link
                href={`/api/crm/dashboard/export?section=pipeline-funnel&format=csv${
                  exportQuery ? `&${exportQuery}` : ''
                }`}
              >
                <Icons.download className='mr-2 h-4 w-4' /> ส่งออก CSV Funnel
              </Link>
            </Button>
          </>
        ) : null}
      </div>
    </div>
  );
}
