/**
 * filekorolheader: 搜索表单分页公共组件 - 提供可复用的搜索、表单和分页功能
 * 功能：搜索条件管理、表头渲染、分页控制、加载状态处理
 * 路径：/components/common/searchFormPagination
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式，支持完全自定义配置
 */
'use client';

import { useState, useEffect, useMemo, useCallback } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { AlertCircle, ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

import { SearchFormComponent } from './components/SearchFormComponent';
import { PaginationComponent } from './components/PaginationComponent';

// 搜索条件配置接口
export interface SearchFieldConfig {
  key: string;
  label: string;
  type: 'text' | 'select';
  placeholder?: string;
  options?: Array<{ value: string; label: string }>;
  defaultValue?: string;
}

// 表头配置接口
export interface TableColumnConfig {
  key: string;
  label: string;
  width?: string;
  render?: (value: any, row: any, index: number) => React.ReactNode;
}

// 分页配置接口
export interface PaginationConfig {
  page: number;
  size: number;
  total: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

// 组件Props接口 - 简化版本
export interface SearchFormPaginationProps<T = any> {
  // 搜索表单配置
  formTitle?: string;
  formRightContent?: React.ReactNode;
  searchFields: SearchFieldConfig[];
  searchPlaceholder?: string;
  onSearch?: (filters: Record<string, string>) => void;

  // 表格配置
  columns: TableColumnConfig[];
  data?: T[];
  loading?: boolean;
  error?: string | null;

  // 分页配置
  pagination?: PaginationConfig;
  onPageChange?: (page: number) => void;
  onSizeChange?: (size: number) => void;

  // 空状态配置
  emptyIcon?: React.ReactNode;
  emptyText?: string;

  // 分页器配置
  showSizeSelector?: boolean;
  showPageInfo?: boolean;
  showQuickJumper?: boolean;
  sizeOptions?: number[];
  maxVisiblePages?: number;

  // 自定义样式
  className?: string;

  // 数据更新回调 - 用于父组件获取搜索条件变化
  onDataUpdate?: (data: {
    items: T[];
    pagination: PaginationConfig;
    loading: boolean;
    error: string | null;
  }) => void;
}

export function SearchFormPagination<T = any>({
  formTitle,
  formRightContent,
  searchFields,
  searchPlaceholder = '请输入搜索关键词...',
  onSearch,
  columns,
  data = [],
  loading = false,
  error = null,
  pagination,
  onPageChange,
  onSizeChange,
  emptyIcon,
  emptyText = '暂无数据',
  showSizeSelector = true,
  showPageInfo = true,
  showQuickJumper = false,
  sizeOptions = [10, 30, 50, 100],
  maxVisiblePages = 7,
  className = '',
  onDataUpdate,
}: SearchFormPaginationProps<T>) {
  // 简化的内部状态 - 只管理搜索条件
  const [filters, setFilters] = useState<Record<string, string>>(
    searchFields.reduce((acc, field) => {
      acc[field.key] = field.defaultValue || '';
      return acc;
    }, {} as Record<string, string>)
  );

  // 数据更新回调 - 通知父组件数据变化
  useEffect(() => {
    onDataUpdate?.({
      items: data,
      pagination: pagination || {
        page: 1,
        size: 10,
        total: 0,
        totalPages: 0,
        hasNext: false,
        hasPrev: false,
      },
      loading,
      error,
    });
  }, [data, pagination, loading, error, onDataUpdate]);

  // 简化的事件处理器 - 纯粹的状态通知
  const handleSearch = useCallback((newFilters: Record<string, string>) => {
    setFilters(newFilters);
    onSearch?.(newFilters);
  }, [onSearch]);

  const handlePageChange = useCallback((page: number) => {
    onPageChange?.(page);
  }, [onPageChange]);

  const handleSizeChange = useCallback((size: number) => {
    onSizeChange?.(size);
  }, [onSizeChange]);

  // 稳定的filters引用
  const stableFilters = useMemo(() => filters, [filters]);

  // 渲染表头
  const renderTableHeader = () => {
    // 计算列宽：对于自定义渲染的列，使用最小宽度；对于简单列，根据内容计算宽度
    const getColumnWidth = (column: TableColumnConfig) => {
      if (column.width) {
        return column.width; // 如果明确指定了宽度，使用指定宽度
      }

      // 对于简单文本列，计算内容长度并设置合理的最小宽度
      if (!column.render) {
        return 'min-w-[100px] max-w-[200px]'; // 普通文本列的宽度范围
      }

      // 对于自定义渲染的列，给一个合理的最小宽度
      return 'min-w-[120px] max-w-[300px]'; // 自定义列的宽度范围
    };

    return (
      <TableHeader>
        <TableRow>
          {columns.map((column) => (
            <TableHead
              key={column.key}
              style={{
                width: getColumnWidth(column),
                minWidth: column.render ? '120px' : '100px',
                maxWidth: column.render ? '300px' : '200px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
              }}
            >
              <div className="truncate" title={column.label}>
                {column.label}
              </div>
            </TableHead>
          ))}
        </TableRow>
      </TableHeader>
    );
  };

  // 渲染表格行
  const renderTableRow = (row: T, index: number) => (
    <TableRow key={index}>
      {columns.map((column) => (
        <TableCell
          key={column.key}
          style={{
            maxWidth: column.render ? '300px' : '200px',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
          }}
        >
          <div className="truncate" title={
            column.render
              ? (column.render(row[column.key as keyof T], row, index) as any)?.toString() || ''
              : String(row[column.key as keyof T] ?? '-')
          }>
            {column.render
              ? column.render(row[column.key as keyof T], row, index)
              : String(row[column.key as keyof T] ?? '-')}
          </div>
        </TableCell>
      ))}
    </TableRow>
  );

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 搜索表单和数据表格在同一个Card里面 */}
      <Card className="p-6 bg-card">
        {/* 搜索表单 - 左右两部分布局 */}
        {(formTitle || formRightContent || searchFields.length > 0) && (
          <div className="flex items-center justify-between mb-4">
            {/* 左侧 - 表单名称 */}
            {formTitle && (
              <h3 className="text-lg font-semibold text-foreground">{formTitle}</h3>
            )}

            {/* 右侧 - 搜索控件和自定义内容 */}
            <div className="flex items-center gap-3">
              <SearchFormComponent
                key="search-form"
                fields={searchFields}
                filters={stableFilters}
                onFiltersChange={handleSearch}
                placeholder={searchPlaceholder}
                loading={loading}
              />
              {formRightContent}
            </div>
          </div>
        )}

        {/* 错误状态 */}
        {error && (
          <div className="mb-4 p-4 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-lg">
            <div className="flex items-center gap-2 text-red-600 dark:text-red-400">
              <AlertCircle className="w-4 h-4" />
              <span>{error}</span>
            </div>
          </div>
        )}

        {/* 数据表格 */}
        {!error && (
          <>
            {/* 初始加载状态 */}
            {loading && data.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <RefreshCw className="w-8 h-8 mx-auto mb-2 animate-spin" />
                <p>加载中...</p>
              </div>
            ) : (
              <>
                {/* 表格加载遮罩 */}
                <div className="relative">
                  {loading && (
                    <div className="absolute inset-0 bg-white/50 dark:bg-black/50 backdrop-blur-sm z-10 flex items-center justify-center rounded-lg">
                      <div className="flex flex-col items-center text-muted-foreground">
                        <RefreshCw className="w-6 h-6 animate-spin mb-2" />
                        <p className="text-sm">加载中...</p>
                      </div>
                    </div>
                  )}

                  <div className="border rounded-lg overflow-hidden">
                    <Table>
                      {renderTableHeader()}
                      <TableBody>
                        {data.map((row, index) => renderTableRow(row, index))}
                      </TableBody>
                    </Table>
                  </div>
                </div>

                {/* 空状态 */}
                {data.length === 0 && !loading && (
                  <div className="text-center py-12 text-muted-foreground">
                    {emptyIcon || <div className="w-12 h-12 mx-auto mb-4 opacity-20" />}
                    <p>{emptyText}</p>
                  </div>
                )}

                {/* 分页组件 */}
                {pagination && (
                  <PaginationComponent
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onSizeChange={handleSizeChange}
                    loading={loading}
                    showSizeSelector={showSizeSelector}
                    showPageInfo={showPageInfo}
                    showQuickJumper={showQuickJumper}
                    sizeOptions={sizeOptions}
                    maxVisiblePages={maxVisiblePages}
                  />
                )}
              </>
            )}
          </>
        )}
      </Card>
    </div>
  );
}

export default SearchFormPagination;