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

import { useState, useEffect, useMemo, useCallback, useRef } 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;
}

// URL 参数同步配置
export interface UrlSyncConfig {
  // 是否启用 URL 参数同步（默认为true，只有传false才禁用）
  enabled?: boolean;
  // 是否在初始化时检测空 URL 并添加默认参数（默认为true）
  initWithDefaults?: boolean;
  // 默认分页参数（默认为 { page: 1, size: 10 }）
  defaultPagination?: {
    page: number;
    size: number;
  };
  // URL 更新防抖时间（毫秒，默认为300）
  updateDebounce?: number;
  // 自定义 URL 参数名映射（可选，不配置则自动从 searchFields 提取）
  paramNames?: {
    page?: string;
    size?: string;
    [key: string]: string | undefined;
  };
}

// 组件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;

  // URL 参数同步配置
  urlSync?: UrlSyncConfig;

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

  // URL 状态变化回调 - 用于父组件监听 URL 参数变化（可选）
  onUrlStateChange?: (urlState: {
    filters: Record<string, string>;
    pagination: {
      page: number;
      size: number;
    };
  }) => 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 = '',
  urlSync,
  onDataUpdate,
  onUrlStateChange,
}: SearchFormPaginationProps<T>) {
  // URL 同步配置 - 自动从 searchFields 提取参数映射
  const urlConfig = useMemo(() => {
    // 默认启用URL同步，除非明确禁用
    const isEnabled = urlSync?.enabled !== false; // 默认为true，只有明确传false才禁用

    // 如果启用 URL 同步，自动生成参数映射
    const autoParamNames = isEnabled ? {
      page: urlSync?.paramNames?.page ?? 'page',
      size: urlSync?.paramNames?.size ?? 'size',
      // 从 searchFields 自动提取参数映射
      ...Object.fromEntries(
        searchFields.map(field => [
          field.key,
          urlSync?.paramNames?.[field.key] ?? field.key  // 优先使用自定义映射，否则使用字段 key
        ])
      )
    } : {};

    return {
      enabled: isEnabled,
      paramNames: autoParamNames,
      initWithDefaults: urlSync?.initWithDefaults ?? true, // 默认为true
      defaultPagination: urlSync?.defaultPagination ?? { page: 1, size: 10 },
      updateDebounce: urlSync?.updateDebounce ?? 300 // 默认300ms
    };
  }, [urlSync, searchFields]);

  // URL 参数解析和同步相关的 ref
  const isInitializingRef = useRef(false);
  const lastUrlStateRef = useRef<string>('');

  // 更新来源跟踪 - 用于区分不同类型的更新
  const updateSourceRef = useRef<'user' | 'parent' | 'url' | 'init'>('init');

  // 简化的内部状态 - 只管理搜索条件
  const [filters, setFilters] = useState<Record<string, string>>(() => {
    // 初始化时从 URL 读取参数（如果启用 URL 同步）
    if (urlConfig.enabled && typeof window !== 'undefined') {
      const urlParams = new URLSearchParams(window.location.search);
      const initialFilters: Record<string, string> = {};

      // 从 URL 中读取搜索字段参数
      searchFields.forEach(field => {
        const paramValue = urlParams.get(urlConfig.paramNames[field.key] || field.key);
        if (paramValue) {
          initialFilters[field.key] = paramValue;
        } else {
          initialFilters[field.key] = field.defaultValue || '';
        }
      });

      return initialFilters;
    }

    // 默认初始化逻辑
    return searchFields.reduce((acc, field) => {
      acc[field.key] = field.defaultValue || '';
      return acc;
    }, {} as Record<string, string>);
  });

  // URL 更新函数 - 事件驱动模型，移除防抖
  const updateUrl = useCallback((
    newFilters: Record<string, string>,
    newPagination?: { page: number; size: number },
    source: 'user' | 'parent' | 'url' | 'init' = 'user'
  ) => {
    if (!urlConfig.enabled || typeof window === 'undefined') return;

    // 设置更新来源
    updateSourceRef.current = source;

    // 立即执行URL更新，不使用防抖
    try {
      const url = new URL(window.location.href);
      const urlParams = url.searchParams;

      console.log(`开始更新URL - 来源: ${source}`, { newFilters, newPagination });

      // 更新搜索参数
      Object.entries(newFilters).forEach(([key, value]) => {
        const paramName = urlConfig.paramNames[key] || key;
        if (value && value !== '') {
          urlParams.set(paramName, value);
        } else {
          urlParams.delete(paramName);
        }
      });

      // 更新分页参数
      if (newPagination) {
        urlParams.set(urlConfig.paramNames.page, newPagination.page.toString());
        urlParams.set(urlConfig.paramNames.size, newPagination.size.toString());
      }

      // 构建新的 URL 状态字符串
      const newUrlState = urlParams.toString();

      // 只有在 URL 状态发生变化时才更新
      if (newUrlState !== lastUrlStateRef.current) {
        lastUrlStateRef.current = newUrlState;

        // 更新浏览器历史记录
        window.history.replaceState({}, '', url.toString());

        // 只有在 URL 变化时才通知父组件（避免循环调用）
        // 用户操作和父组件更新不需要触发 onUrlStateChange
        // 只有 URL 本身变化（如浏览器前进后退）才需要触发
        if (source === 'url' && !isInitializingRef.current) {
          onUrlStateChange?.({
            filters: newFilters,
            pagination: newPagination || urlConfig.defaultPagination
          });
        }
      }
    } catch (error) {
      console.error('Failed to update URL:', error);
    }
  }, [urlConfig, onUrlStateChange]);

  // 内部状态管理
  const [internalPagination, setInternalPagination] = useState<{ page: number; size: number }>(
    urlConfig.defaultPagination
  );

  // 从 URL 读取分页参数的函数
  const readPaginationFromUrl = useCallback((): { page: number; size: number } => {
    if (!urlConfig.enabled || typeof window === 'undefined') {
      return urlConfig.defaultPagination;
    }

    try {
      const urlParams = new URLSearchParams(window.location.search);
      const urlPage = urlParams.get(urlConfig.paramNames.page);
      const urlSize = urlParams.get(urlConfig.paramNames.size);

      return {
        page: urlPage ? Math.max(1, parseInt(urlPage, 10) || 1) : urlConfig.defaultPagination.page,
        size: urlSize ? Math.max(1, parseInt(urlSize, 10) || 10) : urlConfig.defaultPagination.size
      };
    } catch (error) {
      console.error('Failed to read pagination from URL:', error);
      return urlConfig.defaultPagination;
    }
  }, [urlConfig]);

  
  // 初始化 URL 参数检测和默认值设置
  useEffect(() => {
    if (!urlConfig.enabled || typeof window === 'undefined' || isInitializingRef.current) return;

    isInitializingRef.current = true;

    try {
      const urlParams = new URLSearchParams(window.location.search);
      const hasSearchParams = urlParams.toString() !== '';

      console.log('URL同步初始化 - 当前URL参数:', Object.fromEntries(urlParams.entries()));
      console.log('URL同步初始化 - 是否有URL参数:', hasSearchParams);

      // 如果 URL 没有参数且配置要求初始化默认值
      if (!hasSearchParams && urlConfig.initWithDefaults) {
        const url = new URL(window.location.href);

        // 始终设置默认分页参数到URL，不管是否为默认值
        urlParams.set(urlConfig.paramNames.page, urlConfig.defaultPagination.page.toString());
        urlParams.set(urlConfig.paramNames.size, urlConfig.defaultPagination.size.toString());

        // 设置默认搜索字段值 - 优先使用searchFields的defaultValue
        searchFields.forEach(field => {
          const fieldValue = filters[field.key] || field.defaultValue || '';
          if (fieldValue !== '') {
            const paramName = urlConfig.paramNames[field.key] || field.key;
            urlParams.set(paramName, fieldValue);
          }
        });

        if (urlParams.toString() !== '') {
          url.search = urlParams.toString();
          window.history.replaceState({}, '', url.toString());
        }
      }

      // 从URL读取过滤条件和分页参数
      const urlFilters: Record<string, string> = {};
      let hasUrlFilters = false;

      searchFields.forEach(field => {
        const paramValue = urlParams.get(urlConfig.paramNames[field.key] || field.key);
        if (paramValue) {
          urlFilters[field.key] = paramValue;
          hasUrlFilters = true;
        }
      });

      const urlPagination = readPaginationFromUrl();
      console.log('URL同步初始化 - 从URL读取的过滤条件:', urlFilters);
      console.log('URL同步初始化 - 从URL读取的分页参数:', urlPagination);

      // 设置内部分页状态
      setInternalPagination(urlPagination);

      // URL中有参数时，自动同步到内部状态并通知父组件
      if (hasUrlFilters || hasSearchParams) {
        const finalFilters = hasUrlFilters ? urlFilters : filters;
        console.log('URL同步初始化 - 同步参数到内部状态:', {
          filters: finalFilters,
          pagination: urlPagination
        });

        // 更新内部状态
        if (hasUrlFilters) {
          setFilters(finalFilters);
        }

        // 通知父组件URL状态变化（标记为初始化）
        // 使用下一个事件循环确保状态已更新
        Promise.resolve().then(() => {
          if (!isInitializingRef.current) {
            onUrlStateChange?.({
              filters: finalFilters,
              pagination: urlPagination
            });
          }
        });
      }
    } catch (error) {
      console.error('Failed to initialize URL parameters:', error);
    }
  }, [urlConfig, filters, searchFields, readPaginationFromUrl]);

  // 监听父组件传入的分页状态变化 - 同步到内部状态和URL
  useEffect(() => {
    if (pagination && urlConfig.enabled && !isInitializingRef.current) {
      console.log('父组件分页状态变化:', pagination);

      // 如果父组件的分页状态与内部状态不一致，同步内部状态
      if (pagination.page !== internalPagination.page || pagination.size !== internalPagination.size) {
        setInternalPagination({
          page: pagination.page,
          size: pagination.size
        });

        // 同步到URL（标记为父组件更新）
        updateUrl(filters, pagination, 'parent');
      }
    }
  }, [pagination, filters, urlConfig.enabled, updateUrl, internalPagination.page, internalPagination.size]);

  // 监听浏览器前进后退事件
  useEffect(() => {
    if (!urlConfig.enabled || typeof window === 'undefined') return;

    const handlePopState = (event: PopStateEvent) => {
      console.log('浏览器前进后退事件触发:', event);

      const urlParams = new URLSearchParams(window.location.search);
      const newFilters: Record<string, string> = {};

      // 从 URL 中读取搜索字段参数
      searchFields.forEach(field => {
        const paramValue = urlParams.get(urlConfig.paramNames[field.key] || field.key);
        if (paramValue) {
          newFilters[field.key] = paramValue;
        } else {
          newFilters[field.key] = field.defaultValue || '';
        }
      });

      const newPagination = {
        page: Math.max(1, parseInt(urlParams.get(urlConfig.paramNames.page) || '1', 10)),
        size: Math.max(1, parseInt(urlParams.get(urlConfig.paramNames.size) || '10', 10))
      };

      console.log('从URL恢复状态:', { newFilters, newPagination });

      // 更新内部状态（标记为URL变化）
      setFilters(newFilters);
      setInternalPagination(newPagination);

      // 通知父组件 URL 状态变化（只有URL来源的变化才触发）
      onUrlStateChange?.({
        filters: newFilters,
        pagination: newPagination
      });
    };

    window.addEventListener('popstate', handlePopState);

    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, [urlConfig, searchFields, onUrlStateChange]);

  
  // 重置初始化标志 - 确保在初始化完成后允许 URL 更新
  useEffect(() => {
    if (isInitializingRef.current) {
      // 立即重置初始化标志，不使用延迟
      isInitializingRef.current = false;
    }
  }, []);

  // 数据更新回调 - 通知父组件数据变化
  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>) => {
    console.log('用户搜索操作:', newFilters);

    // 更新内部状态
    setFilters(newFilters);

    // 搜索时重置到第1页，保持当前每页大小
    const newPagination = { page: 1, size: internalPagination.size };
    setInternalPagination(newPagination);

    // 通知父组件搜索条件变化
    onSearch?.(newFilters);

    // 同步到URL（标记为用户操作）
    updateUrl(newFilters, newPagination, 'user');
  }, [internalPagination.size, onSearch, updateUrl]);

  const handlePageChange = useCallback((page: number) => {
    console.log('用户分页操作:', page);

    const newPagination = { ...internalPagination, page };

    // 更新内部状态
    setInternalPagination(newPagination);

    // 通知父组件分页变化
    onPageChange?.(page);

    // 同步到URL（标记为用户操作）
    updateUrl(filters, newPagination, 'user');
  }, [internalPagination, filters, onPageChange, updateUrl]);

  const handleSizeChange = useCallback((size: number) => {
    console.log('用户修改每页大小:', size);

    // 修改每页大小时重置到第1页
    const newPagination = { page: 1, size };

    // 更新内部状态
    setInternalPagination(newPagination);

    // 通知父组件每页大小变化
    onSizeChange?.(size);

    // 同步到URL（标记为用户操作）
    updateUrl(filters, newPagination, 'user');
  }, [filters, onSizeChange, updateUrl]);

  // 稳定的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;