import { CalendarDays, ChevronDown, RefreshCw, Search } from 'lucide-react';
import type { DateRange } from 'react-day-picker';

import { BatchIdCombobox, type BatchIdComboboxOption } from '@/components/shared/BatchIdCombobox';
import { searchFieldClassName } from '@/components/shared/searchFieldStyles';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

export interface MaterialFilterBarProps {
  /** 批次过滤；空字符串表示不过滤 */
  searchBatchId: string;
  /** 来源文件 substring */
  searchSourceFile: string;
  /** 物料名称 substring */
  searchName: string;
  /** 创建人 substring */
  searchCreatedBy: string;
  /** 日期文本输入框值（"YYYYMMDD-YYYYMMDD" 等紧凑格式） */
  searchCreatedAtRange: string;
  /** 是否展开第二行字段（来源文件 / 创建人）*/
  searchExpanded: boolean;
  /** 日历 popover 开关 */
  createdAtPickerOpen: boolean;
  /** 已选择的日期区间，用于回填 Calendar */
  selectedCreatedAtRange: DateRange | undefined;
  /** 批次下拉选项 */
  procurementBatchOptions: BatchIdComboboxOption[];

  onSearchBatchIdChange: (value: string) => void;
  onSearchSourceFileChange: (value: string) => void;
  onSearchNameChange: (value: string) => void;
  onSearchCreatedByChange: (value: string) => void;
  onCreatedAtRangeChange: (value: string) => void;
  onCreatedAtRangeSelect: (range: DateRange | undefined) => void;
  onSearchExpandedChange: (value: boolean) => void;
  onCreatedAtPickerOpenChange: (value: boolean) => void;
  onResetFilters: () => void;
}

export function MaterialFilterBar({
  searchBatchId,
  searchSourceFile,
  searchName,
  searchCreatedBy,
  searchCreatedAtRange,
  searchExpanded,
  createdAtPickerOpen,
  selectedCreatedAtRange,
  procurementBatchOptions,
  onSearchBatchIdChange,
  onSearchSourceFileChange,
  onSearchNameChange,
  onSearchCreatedByChange,
  onCreatedAtRangeChange,
  onCreatedAtRangeSelect,
  onSearchExpandedChange,
  onCreatedAtPickerOpenChange,
  onResetFilters,
}: MaterialFilterBarProps) {
  return (
    <div className="mb-3 shrink-0 flex items-start gap-4 w-full">
      {/* 两行字段共享同一套列，保证垂直对齐 */}
      <div className="grid grid-cols-[max-content_10rem_max-content_10rem_max-content_14.5rem] gap-x-3 gap-y-2 items-center flex-none">
        {/* 第一行 */}
        <span className="text-sm text-muted-foreground">批次ID</span>
        <BatchIdCombobox
          value={searchBatchId}
          onChange={onSearchBatchIdChange}
          options={procurementBatchOptions}
          className="w-44"
        />
        <span className="text-sm text-muted-foreground pl-4">材料名称</span>
        <Input
          placeholder="请输入材料名称"
          value={searchName}
          onChange={e => onSearchNameChange(e.target.value)}
          className={searchFieldClassName}
        />
        <span className="text-sm text-muted-foreground pl-4">创建时间</span>
        <div className="flex items-center gap-1.5 w-[14.5rem]">
          <Input
            placeholder="如 20260404-20260406"
            value={searchCreatedAtRange}
            onChange={e => onCreatedAtRangeChange(e.target.value)}
            className={`${searchFieldClassName} min-w-0`}
          />
          <Popover open={createdAtPickerOpen} onOpenChange={onCreatedAtPickerOpenChange}>
            <PopoverTrigger asChild>
              <Button variant="outline" size="icon" className="h-9 w-9 shrink-0" aria-label="选择创建日期区间">
                <CalendarDays className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent align="end" className="w-auto border-[hsl(220_13%_91%)] bg-white p-0 text-[hsl(222_47%_11%)]">
              <Calendar
                mode="range"
                selected={selectedCreatedAtRange}
                onSelect={onCreatedAtRangeSelect}
                numberOfMonths={2}
                className="bg-white text-[hsl(222_47%_11%)]"
                classNames={{
                  caption_label: 'text-sm font-medium text-[hsl(222_47%_11%)]',
                  head_cell: 'w-9 rounded-md text-[0.8rem] font-normal text-[hsl(215_16%_47%)]',
                  nav_button: 'inline-flex h-7 w-7 items-center justify-center rounded-md border border-[hsl(220_13%_91%)] bg-white p-0 text-[hsl(222_47%_11%)] hover:bg-[hsl(221_83%_95%)] hover:text-[hsl(221_83%_40%)]',
                  cell: 'relative h-9 w-9 p-0 text-center text-sm [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-[hsl(221_83%_95%/0.5)] [&:has([aria-selected])]:bg-[hsl(221_83%_95%)] first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20',
                  day: 'inline-flex h-9 w-9 items-center justify-center rounded-md p-0 font-normal text-[hsl(222_47%_11%)] hover:bg-[hsl(221_83%_95%)] hover:text-[hsl(221_83%_40%)] aria-selected:opacity-100',
                  day_selected: 'bg-[hsl(221_83%_53%)] text-white hover:bg-[hsl(221_83%_53%)] hover:text-white focus:bg-[hsl(221_83%_53%)] focus:text-white',
                  day_today: 'bg-[hsl(221_83%_95%)] text-[hsl(221_83%_40%)]',
                  day_outside: 'text-[hsl(215_16%_47%)] opacity-50 aria-selected:bg-[hsl(221_83%_95%/0.5)] aria-selected:text-[hsl(215_16%_47%)] aria-selected:opacity-30',
                  day_disabled: 'text-[hsl(215_16%_47%)] opacity-50',
                  day_range_middle: 'aria-selected:bg-[hsl(221_83%_95%)] aria-selected:text-[hsl(221_83%_40%)]',
                }}
                initialFocus
              />
            </PopoverContent>
          </Popover>
        </div>
        {/* 展开第二行 */}
        {searchExpanded && (
          <>
            <span className="text-sm text-muted-foreground">来源文件</span>
            <Input
              placeholder="请输入来源文件"
              value={searchSourceFile}
              onChange={e => onSearchSourceFileChange(e.target.value)}
              className={searchFieldClassName}
            />
            <span className="text-sm text-muted-foreground pl-4">创建人</span>
            <Input
              placeholder="请输入创建人"
              value={searchCreatedBy}
              onChange={e => onSearchCreatedByChange(e.target.value)}
              className={searchFieldClassName}
            />
            <span /><span />
          </>
        )}
      </div>
      {/* 按钮组：固定在右侧，顶对齐 */}
      <div className="flex items-center gap-2 shrink-0 self-start ml-auto">
        <button
          type="button"
          onClick={() => onSearchExpandedChange(!searchExpanded)}
          className="flex items-center gap-0.5 text-sm text-primary hover:text-primary/80 transition-colors"
        >
          {searchExpanded ? '收起' : '展开'}
          <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${searchExpanded ? 'rotate-180' : ''}`} />
        </button>
        <Button variant="outline" size="sm" className="h-9" onClick={onResetFilters}>
          <RefreshCw className="h-3.5 w-3.5 mr-1" />重置
        </Button>
        <Button size="sm" className="h-9">
          <Search className="h-3.5 w-3.5 mr-1" />查询
        </Button>
      </div>
    </div>
  );
}
