"use client";

import { useState, useEffect } from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { SortableRowItem } from "./sortable-row-item";

// 表格行配置接口
export interface TableRowConfig {
  rowId: string;
  isVisible: boolean;
  displayOrder?: number;
  isCustomRow?: boolean;
  customRowType?: 'empty' | 'separator' | 'note';
}

// 行设置组件属性
export interface RowSettingsProps {
  rowId: string;
  displayText: string;
  isVisible: boolean;
  onVisibilityChange: (rowId: string, visible: boolean) => void;
}

// 配置面板属性
export interface RowSettingsPanelProps {
  isOpen: boolean;
  onClose: () => void;
  rowConfigs: Record<string, TableRowConfig>;
  rowDisplayTexts: Record<string, string>;
  onConfigChange: (configs: Record<string, TableRowConfig>) => void;
  onRowOrderChange?: (newOrder: string[]) => void;
  onDeleteCustomRow?: (rowId: string) => void;
  enableRowReordering?: boolean;
}

// 单个行设置组件
export function RowSettings({
  rowId,
  displayText,
  isVisible,
  onVisibilityChange
}: RowSettingsProps) {
  return (
    <div className={cn(
      "flex items-center justify-between py-3 px-4 hover:bg-gray-50 rounded-lg transition-colors border",
      isVisible ? "border-green-200 bg-green-50/30" : "border-gray-200 bg-gray-50/30"
    )}>
      <div className="flex items-center gap-3 flex-1 min-w-0">
        <div className={cn(
          "w-2 h-2 rounded-full flex-shrink-0",
          isVisible ? "bg-green-500" : "bg-gray-400"
        )} />
        <span className={cn(
          "text-sm font-medium truncate",
          isVisible ? "text-gray-900" : "text-gray-500"
        )}>
          {displayText}
        </span>
      </div>
      <label className="flex items-center cursor-pointer ml-3">
        <input
          type="checkbox"
          checked={isVisible}
          onChange={(e) => onVisibilityChange(rowId, e.target.checked)}
          className="sr-only"
        />
        <div className={cn(
          "relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 ease-in-out focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2",
          isVisible ? "bg-blue-600" : "bg-gray-300"
        )}>
          <span className={cn(
            "inline-block h-5 w-5 transform rounded-full bg-white shadow-lg transition-transform duration-200 ease-in-out",
            isVisible ? "translate-x-5" : "translate-x-0.5"
          )} />
        </div>
      </label>
    </div>
  );
}

// 配置面板组件
export function RowSettingsPanel({
  isOpen,
  onClose,
  rowConfigs,
  rowDisplayTexts,
  onConfigChange,
  onRowOrderChange,
  onDeleteCustomRow,
  enableRowReordering = true
}: RowSettingsPanelProps) {
  const [localConfigs, setLocalConfigs] = useState(() => rowConfigs);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

  // Sync local configs when panel opens
  useEffect(() => {
    if (isOpen) {
      setLocalConfigs(rowConfigs);
    }
  }, [isOpen, rowConfigs]);

  const handleVisibilityChange = (rowId: string, visible: boolean) => {
    try {
      // 如果要隐藏行，检查是否会导致所有行都被隐藏
      if (!visible) {
        const currentVisibleCount = Object.values(localConfigs).filter(config => config.isVisible).length;
        if (currentVisibleCount <= 1) {
          // 防止隐藏最后一个可见行
          console.warn('Cannot hide the last visible row');
          return;
        }
      }

      const newConfigs = {
        ...localConfigs,
        [rowId]: {
          ...localConfigs[rowId],
          rowId,
          isVisible: visible
        }
      };
      setLocalConfigs(newConfigs);
      onConfigChange(newConfigs);
    } catch (error) {
      console.error('Failed to change row visibility:', error);
    }
  };

  const handleShowAll = () => {
    try {
      const newConfigs = { ...localConfigs };
      Object.keys(newConfigs).forEach(rowId => {
        newConfigs[rowId] = { ...newConfigs[rowId], isVisible: true };
      });
      setLocalConfigs(newConfigs);
      onConfigChange(newConfigs);
    } catch (error) {
      console.error('Failed to show all rows:', error);
    }
  };

  const handleHideAll = () => {
    try {
      const newConfigs = { ...localConfigs };
      const configKeys = Object.keys(newConfigs);
      
      // 防止隐藏所有行（至少保留一行可见）
      if (configKeys.length <= 1) {
        return; // 如果只有一行或没有行，不执行隐藏全部
      }
      
      configKeys.forEach(rowId => {
        newConfigs[rowId] = { ...newConfigs[rowId], isVisible: false };
      });
      
      setLocalConfigs(newConfigs);
      onConfigChange(newConfigs);
    } catch (error) {
      console.error('Failed to hide all rows:', error);
    }
  };

  const handleReset = () => {
    try {
      const newConfigs = { ...localConfigs };
      Object.keys(newConfigs).forEach(rowId => {
        newConfigs[rowId] = { ...newConfigs[rowId], isVisible: true };
      });
      setLocalConfigs(newConfigs);
      onConfigChange(newConfigs);
    } catch (error) {
      console.error('Failed to reset configuration:', error);
    }
  };

  // 拖拽排序处理
  const handleDragStart = (index: number) => {
    setDraggedIndex(index);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
    setDragOverIndex(null);
  };

  const handleDragEnter = (index: number) => {
    setDragOverIndex(index);
  };

  const handleDragLeave = () => {
    setDragOverIndex(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const handleDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();
    
    if (draggedIndex === null || draggedIndex === dropIndex) {
      return;
    }

    try {
      const sortedEntries = Object.entries(localConfigs)
        .sort(([, a], [, b]) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0));
      
      const [draggedItem] = sortedEntries.splice(draggedIndex, 1);
      sortedEntries.splice(dropIndex, 0, draggedItem);

      const newConfigs = { ...localConfigs };
      sortedEntries.forEach(([rowId], index) => {
        newConfigs[rowId] = { ...newConfigs[rowId], displayOrder: index };
      });

      setLocalConfigs(newConfigs);
      onConfigChange(newConfigs);
      
      if (onRowOrderChange) {
        const newOrder = sortedEntries.map(([rowId]) => rowId);
        onRowOrderChange(newOrder);
      }
    } catch (error) {
      console.error('Failed to reorder rows:', error);
    }
  };

  // 删除自定义行处理
  const handleDeleteCustomRow = (rowId: string) => {
    try {
      if (onDeleteCustomRow) {
        onDeleteCustomRow(rowId);
      }
      
      const newConfigs = { ...localConfigs };
      delete newConfigs[rowId];
      setLocalConfigs(newConfigs);
      onConfigChange(newConfigs);
    } catch (error) {
      console.error('Failed to delete custom row:', error);
    }
  };

  if (!isOpen) return null;

  const visibleCount = Object.values(localConfigs).filter(config => config.isVisible).length;
  const totalCount = Object.keys(localConfigs).length;
  const canHideMore = visibleCount > 1;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] flex flex-col animate-in fade-in-0 zoom-in-95 duration-200">
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 sm:p-6 border-b">
          <div>
            <h3 className="text-lg font-semibold text-gray-900">表格行设置</h3>
            <p className="text-sm text-gray-500 mt-1">
              显示 {visibleCount} / {totalCount} 行
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors p-1 hover:bg-gray-100 rounded"
          >
            <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
          </button>
        </div>

        {/* 操作按钮 */}
        <div className="flex flex-col sm:flex-row gap-2 p-4 sm:p-6 border-b bg-gray-50">
          <Button
            variant="outline"
            size="sm"
            onClick={handleShowAll}
            className="flex-1 text-xs sm:text-sm"
          >
            <svg className="h-4 w-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
            </svg>
            全部显示
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={handleHideAll}
            disabled={!canHideMore}
            className="flex-1 text-xs sm:text-sm"
            title={!canHideMore ? "至少需要保留一行可见" : "隐藏所有行"}
          >
            <svg className="h-4 w-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
            全部隐藏
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={handleReset}
            className="flex-1 text-xs sm:text-sm"
          >
            <svg className="h-4 w-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clipRule="evenodd" />
            </svg>
            重置
          </Button>
        </div>

        {/* 行配置列表 */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-2">
          {enableRowReordering ? (
            // 可拖拽排序的行列表
            Object.entries(localConfigs)
              .sort(([, a], [, b]) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0))
              .map(([rowId, config], index) => (
                <SortableRowItem
                  key={rowId}
                  rowId={rowId}
                  displayText={rowDisplayTexts[rowId] || rowId}
                  config={config}
                  index={index}
                  isDragging={draggedIndex === index}
                  isDragOver={dragOverIndex === index}
                  onVisibilityChange={handleVisibilityChange}
                  onDragStart={handleDragStart}
                  onDragEnd={handleDragEnd}
                  onDragEnter={handleDragEnter}
                  onDragLeave={handleDragLeave}
                  onDragOver={handleDragOver}
                  onDrop={(e) => handleDrop(e, index)}
                  onDeleteCustomRow={handleDeleteCustomRow}
                  enableDragging={enableRowReordering}
                />
              ))
          ) : (
            // 传统的行列表（不可拖拽）
            Object.entries(localConfigs)
              .sort(([, a], [, b]) => (a.displayOrder ?? 0) - (b.displayOrder ?? 0))
              .map(([rowId, config]) => (
                <RowSettings
                  key={rowId}
                  rowId={rowId}
                  displayText={rowDisplayTexts[rowId] || rowId}
                  isVisible={config.isVisible}
                  onVisibilityChange={handleVisibilityChange}
                />
              ))
          )}
        </div>

        {/* 底部 */}
        <div className="p-4 sm:p-6 border-t bg-gray-50">
          {/* 警告信息 */}
          {visibleCount <= 1 && (
            <div className="mb-3 p-2 bg-yellow-50 border border-yellow-200 rounded text-xs text-yellow-800">
              <div className="flex items-center gap-1">
                <svg className="h-3 w-3 text-yellow-500" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <span>至少需要保留一行可见以确保表格正常显示</span>
              </div>
            </div>
          )}
          
          <div className="flex flex-col sm:flex-row items-center justify-between gap-2">
            <div className="text-xs text-gray-500 text-center sm:text-left">
              配置将自动保存并在下次访问时恢复
            </div>
            <div className="flex items-center gap-2 text-xs text-gray-500">
              <div className="flex items-center gap-1">
                <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                <span>显示 {visibleCount}</span>
              </div>
              <div className="flex items-center gap-1">
                <div className="w-2 h-2 bg-gray-400 rounded-full"></div>
                <span>隐藏 {totalCount - visibleCount}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// 设置按钮组件
export function RowSettingsButton({ onClick }: { onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      className="inline-flex items-center justify-center w-6 h-6 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors"
      title="配置表格行显示"
    >
      <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
        <path fillRule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd" />
      </svg>
    </button>
  );
}