/**
 * 项目-模板绑定列表组件
 * 遵循前端开发规范的组件设计原则
 */

import React, { useState } from 'react';
import {
  Plus,
  Edit2,
  Trash2,
  Power,
  PowerOff,
  Star,
  StarOff,
  Search,
  Filter,
  CheckSquare,
  Square,
  Shuffle
} from 'lucide-react';
import {
  ProjectTemplateBindingDetail,
  BindingType,
  BindingStatus,
  getBindingTypeDisplay,
  getBindingStatusDisplay,
  getBindingTypeColor,
  getBindingStatusColor,
  BINDING_TYPE_OPTIONS,
  BINDING_STATUS_OPTIONS,
} from '../types/projectTemplateBinding';
import { CustomSelect } from './CustomSelect';
import { LoadingSpinner } from './LoadingSpinner';
import { EmptyState } from './EmptyState';
import { DeleteConfirmDialog } from './DeleteConfirmDialog';
import { useNotifications } from './NotificationSystem';

interface ProjectTemplateBindingListProps {
  bindings: ProjectTemplateBindingDetail[];
  loading?: boolean;
  selectedIds?: string[];
  onSelectionChange?: (ids: string[]) => void;
  onAdd?: () => void;
  onEdit?: (binding: ProjectTemplateBindingDetail) => void;
  onDelete?: (id: string) => void;
  onBatchDelete?: (ids: string[]) => void;
  onToggleStatus?: (id: string) => void;
  onSetPrimary?: (projectId: string, templateId: string) => void;
  onMatchMaterials?: (binding: ProjectTemplateBindingDetail) => void;
  searchQuery?: string;
  onSearchChange?: (query: string) => void;
  typeFilter?: BindingType | '';
  onTypeFilterChange?: (type: BindingType | '') => void;
  statusFilter?: BindingStatus | '';
  onStatusFilterChange?: (status: BindingStatus | '') => void;
  activeFilter?: boolean | null;
  onActiveFilterChange?: (active: boolean | null) => void;
}

export const ProjectTemplateBindingList: React.FC<ProjectTemplateBindingListProps> = ({
  bindings,
  loading = false,
  selectedIds = [],
  onSelectionChange,
  onAdd,
  onEdit,
  onDelete,
  onBatchDelete,
  onToggleStatus,
  onSetPrimary,
  onMatchMaterials,
  searchQuery = '',
  onSearchChange,
  typeFilter = '',
  onTypeFilterChange,
  statusFilter = '',
  onStatusFilterChange,
  activeFilter = null,
  onActiveFilterChange,
}) => {
  const { success, error } = useNotifications();
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    id?: string;
    name?: string;
    isBatch?: boolean;
  }>({ isOpen: false });

  // 处理全选/取消全选
  const handleSelectAll = () => {
    if (!onSelectionChange) return;
    
    if (selectedIds.length === bindings.length) {
      onSelectionChange([]);
    } else {
      onSelectionChange(bindings.map(b => b.binding.id));
    }
  };

  // 处理单个选择
  const handleSelectItem = (id: string) => {
    if (!onSelectionChange) return;
    
    if (selectedIds.includes(id)) {
      onSelectionChange(selectedIds.filter(selectedId => selectedId !== id));
    } else {
      onSelectionChange([...selectedIds, id]);
    }
  };

  // 处理删除确认
  const handleDeleteConfirm = (id: string, name: string) => {
    setDeleteConfirm({ isOpen: true, id, name });
  };

  // 处理批量删除确认
  const handleBatchDeleteConfirm = () => {
    setDeleteConfirm({ isOpen: true, isBatch: true });
  };

  // 执行删除
  const executeDelete = async () => {
    try {
      if (deleteConfirm.isBatch && onBatchDelete) {
        await onBatchDelete(selectedIds);
        success('批量删除成功', `已删除 ${selectedIds.length} 个绑定`);
      } else if (deleteConfirm.id && onDelete) {
        await onDelete(deleteConfirm.id);
        success('删除成功', `绑定"${deleteConfirm.name}"已删除`);
      }
    } catch (err) {
      console.error('删除操作失败:', err);
      error('删除失败', err instanceof Error ? err.message : '未知错误');
    } finally {
      setDeleteConfirm({ isOpen: false });
    }
  };

  // 获取过滤选项
  const getTypeFilterOptions = () => [
    { value: '', label: '全部类型' },
    ...BINDING_TYPE_OPTIONS.map(option => ({
      value: option.value,
      label: option.label,
    })),
  ];

  const getStatusFilterOptions = () => [
    { value: '', label: '全部状态' },
    ...BINDING_STATUS_OPTIONS.map(option => ({
      value: option.value,
      label: option.label,
    })),
  ];

  const getActiveFilterOptions = () => [
    { value: '', label: '全部' },
    { value: 'true', label: '已激活' },
    { value: 'false', label: '已停用' },
  ];

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <LoadingSpinner size="large" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 工具栏 */}
      <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
        {/* 搜索和过滤 */}
        <div className="flex flex-1 gap-3 items-center">
          {/* 搜索框 */}
          {onSearchChange && (
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => onSearchChange(e.target.value)}
                placeholder="搜索绑定名称或描述..."
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          )}

          {/* 过滤器 */}
          <div className="flex gap-2 items-center">
            <Filter className="w-4 h-4 text-gray-500" />
            
            {onTypeFilterChange && (
              <CustomSelect
                value={typeFilter}
                onChange={(value) => onTypeFilterChange(value as BindingType | '')}
                options={getTypeFilterOptions()}
                className="min-w-[120px]"
              />
            )}

            {onStatusFilterChange && (
              <CustomSelect
                value={statusFilter}
                onChange={(value) => onStatusFilterChange(value as BindingStatus | '')}
                options={getStatusFilterOptions()}
                className="min-w-[120px]"
              />
            )}

            {onActiveFilterChange && (
              <CustomSelect
                value={activeFilter === null ? '' : activeFilter.toString()}
                onChange={(value) => onActiveFilterChange(value === 'true' ? true : value === 'false' ? false : null)}
                options={getActiveFilterOptions()}
                className="min-w-[100px]"
              />
            )}
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex gap-2 items-center">
          {selectedIds.length > 0 && onBatchDelete && (
            <button
              onClick={handleBatchDeleteConfirm}
              className="px-3 py-2 text-sm font-medium text-red-700 bg-red-50 border border-red-200 rounded-md hover:bg-red-100 transition-colors flex items-center space-x-1"
            >
              <Trash2 className="w-4 h-4" />
              <span>删除选中 ({selectedIds.length})</span>
            </button>
          )}

          {onAdd && (
            <button
              onClick={onAdd}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md hover:bg-blue-700 transition-colors flex items-center space-x-2"
            >
              <Plus className="w-4 h-4" />
              <span>添加绑定</span>
            </button>
          )}
        </div>
      </div>

      {/* 绑定列表 */}
      {bindings.length === 0 ? (
        <EmptyState
          title="暂无模板绑定"
          description="还没有为此项目绑定任何模板，点击上方按钮开始添加。"
          actionText="添加绑定"
          onAction={onAdd || (() => {})}
        />
      ) : (
        <div className="bg-white rounded-lg shadow overflow-hidden">
          {/* 表头 */}
          <div className="bg-gray-50 px-6 py-3 border-b border-gray-200">
            <div className="flex items-center">
              {onSelectionChange && (
                <div className="flex items-center mr-4">
                  <button
                    onClick={handleSelectAll}
                    className="text-gray-500 hover:text-gray-700"
                  >
                    {selectedIds.length === bindings.length ? (
                      <CheckSquare className="w-5 h-5" />
                    ) : (
                      <Square className="w-5 h-5" />
                    )}
                  </button>
                </div>
              )}
              <div className="flex-1 grid grid-cols-12 gap-4 text-xs font-medium text-gray-500 uppercase tracking-wider">
                <div className="col-span-3">模板信息</div>
                <div className="col-span-2">绑定类型</div>
                <div className="col-span-2">状态</div>
                <div className="col-span-1">优先级</div>
                <div className="col-span-2">创建时间</div>
                <div className="col-span-2">操作</div>
              </div>
            </div>
          </div>

          {/* 表体 */}
          <div className="divide-y divide-gray-200">
            {bindings.map((detail) => (
              <BindingListItem
                key={detail.binding.id}
                detail={detail}
                isSelected={selectedIds.includes(detail.binding.id)}
                onSelect={() => handleSelectItem(detail.binding.id)}
                onEdit={onEdit}
                onDelete={(id, name) => handleDeleteConfirm(id, name)}
                onToggleStatus={onToggleStatus}
                onSetPrimary={onSetPrimary}
                onMatchMaterials={onMatchMaterials}
                showSelection={!!onSelectionChange}
              />
            ))}
          </div>
        </div>
      )}

      {/* 删除确认对话框 */}
      <DeleteConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onCancel={() => setDeleteConfirm({ isOpen: false })}
        onConfirm={executeDelete}
        deleting={false}
        title={deleteConfirm.isBatch ? '批量删除绑定' : '删除绑定'}
        message={
          deleteConfirm.isBatch
            ? `确定要删除选中的 ${selectedIds.length} 个绑定吗？此操作不可撤销。`
            : `确定要删除绑定"${deleteConfirm.name}"吗？此操作不可撤销。`
        }
      />
    </div>
  );
};

// 绑定列表项组件
interface BindingListItemProps {
  detail: ProjectTemplateBindingDetail;
  isSelected: boolean;
  onSelect: () => void;
  onEdit?: (binding: ProjectTemplateBindingDetail) => void;
  onDelete?: (id: string, name: string) => void;
  onToggleStatus?: (id: string) => void;
  onSetPrimary?: (projectId: string, templateId: string) => void;
  onMatchMaterials?: (binding: ProjectTemplateBindingDetail) => void;
  showSelection: boolean;
}

const BindingListItem: React.FC<BindingListItemProps> = ({
  detail,
  isSelected,
  onSelect,
  onEdit,
  onDelete,
  onToggleStatus,
  onSetPrimary,
  onMatchMaterials,
  showSelection,
}) => {
  const { binding } = detail;
  const isPrimary = binding.binding_type === BindingType.Primary;

  return (
    <div className="px-6 py-4 hover:bg-gray-50 transition-colors">
      <div className="flex items-center">
        {showSelection && (
          <div className="flex items-center mr-4">
            <button onClick={onSelect} className="text-gray-500 hover:text-gray-700">
              {isSelected ? (
                <CheckSquare className="w-5 h-5 text-blue-600" />
              ) : (
                <Square className="w-5 h-5" />
              )}
            </button>
          </div>
        )}

        <div className="flex-1 grid grid-cols-12 gap-4 items-center">
          {/* 模板信息 */}
          <div className="col-span-3">
            <div className="flex items-center space-x-2">
              {isPrimary && (
                <Star className="w-4 h-4 text-yellow-500 fill-current" />
              )}
              <div>
                <p className="text-sm font-medium text-gray-900">
                  {binding.binding_name || detail.template_name}
                </p>
                <p className="text-xs text-gray-500">{detail.template_name}</p>
              </div>
            </div>
          </div>

          {/* 绑定类型 */}
          <div className="col-span-2">
            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getBindingTypeColor(binding.binding_type)}`}>
              {getBindingTypeDisplay(binding.binding_type)}
            </span>
          </div>

          {/* 状态 */}
          <div className="col-span-2">
            <div className="flex items-center space-x-2">
              <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getBindingStatusColor(binding.binding_status)}`}>
                {getBindingStatusDisplay(binding.binding_status)}
              </span>
              {binding.is_active ? (
                <Power className="w-4 h-4 text-green-500" />
              ) : (
                <PowerOff className="w-4 h-4 text-gray-400" />
              )}
            </div>
          </div>

          {/* 优先级 */}
          <div className="col-span-1">
            <span className="text-sm text-gray-900">{binding.priority}</span>
          </div>

          {/* 创建时间 */}
          <div className="col-span-2">
            <span className="text-sm text-gray-500">
              {new Date(binding.created_at).toLocaleDateString()}
            </span>
          </div>

          {/* 操作 */}
          <div className="col-span-2">
            <div className="flex items-center space-x-2">
              {!isPrimary && onSetPrimary && (
                <button
                  onClick={() => onSetPrimary(binding.project_id, binding.template_id)}
                  className="text-gray-400 hover:text-yellow-500 transition-colors"
                  title="设为主要模板"
                >
                  <StarOff className="w-4 h-4" />
                </button>
              )}

              {onToggleStatus && (
                <button
                  onClick={() => onToggleStatus(binding.id)}
                  className={`transition-colors ${
                    binding.is_active 
                      ? 'text-gray-400 hover:text-red-500' 
                      : 'text-gray-400 hover:text-green-500'
                  }`}
                  title={binding.is_active ? '停用绑定' : '激活绑定'}
                >
                  {binding.is_active ? (
                    <PowerOff className="w-4 h-4" />
                  ) : (
                    <Power className="w-4 h-4" />
                  )}
                </button>
              )}

              {onMatchMaterials && binding.is_active && (
                <button
                  onClick={() => onMatchMaterials(detail)}
                  className="text-gray-400 hover:text-purple-500 transition-colors"
                  title="匹配素材"
                >
                  <Shuffle className="w-4 h-4" />
                </button>
              )}

              {onEdit && (
                <button
                  onClick={() => onEdit(detail)}
                  className="text-gray-400 hover:text-blue-500 transition-colors"
                  title="编辑绑定"
                >
                  <Edit2 className="w-4 h-4" />
                </button>
              )}

              {onDelete && (
                <button
                  onClick={() => onDelete(binding.id, binding.binding_name || detail.template_name)}
                  className="text-gray-400 hover:text-red-500 transition-colors"
                  title="删除绑定"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
