/**
 * filekorolheader: 模型集成管理页面 - AI模型服务与参数管理平台
 * 功能：模型服务列表管理、统计卡片展示、搜索筛选功能、模型操作管理
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用useReducer状态管理，shadcn语义化样式
 */
'use client';

import { useReducer, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import {
  Plus,
  Brain,
  PlayCircle,
  Target,
  Zap,
  Search
} from 'lucide-react';
import { ModelServiceList } from './components/ModelServiceList';
import { ModelAnalytics } from './components/ModelAnalytics';
import { AddModelDialog } from './components/AddModelDialog';
import { ModelConfigDialog } from './components/ModelConfigDialog';
import { DeleteModelDialog } from './components/DeleteModelDialog';
import { PermissionDialog } from './components/PermissionDialog';
import { PerformanceDialog } from './components/PerformanceDialog';
import { RedeployDialog } from './components/RedeployDialog';
import { modelIntegrationReducer, initialState } from './components/modelIntegrationReducer';
import { ModelType, ModelStatus } from './types';

export default function ModelIntegrationPage() {
  const [state, dispatch] = useReducer(modelIntegrationReducer, initialState);

  useEffect(() => {
    dispatch({ type: 'LOAD_DATA' });
  }, []);

  const handleAddModel = () => {
    dispatch({ type: 'SHOW_ADD_MODEL_DIALOG' });
  };

  const handleEditModel = (model: any) => {
    dispatch({ type: 'SHOW_CONFIG_DIALOG', payload: model });
  };

  const handleViewModel = (model: any) => {
    dispatch({ type: 'SHOW_VIEW_DIALOG', payload: model });
  };

  const handleDeleteModel = (model: any) => {
    dispatch({ type: 'SHOW_DELETE_DIALOG', payload: model });
  };

  const handleToggleModel = (modelId: string) => {
    dispatch({ type: 'TOGGLE_MODEL_STATUS', payload: modelId });
  };

  const handlePermission = (model: any) => {
    dispatch({ type: 'SHOW_PERMISSION_DIALOG', payload: model });
  };

  const handlePerformance = (model: any) => {
    dispatch({ type: 'SHOW_PERFORMANCE_DIALOG', payload: model });
  };

  const handleRedeploy = (model: any) => {
    dispatch({ type: 'SHOW_REDEPLOY_DIALOG', payload: model });
  };

  const handleSearchChange = (value: string) => {
    dispatch({ type: 'UPDATE_FILTERS', payload: { searchTerm: value } });
  };

  const handleTypeFilterChange = (value: string) => {
    dispatch({ type: 'UPDATE_FILTERS', payload: { typeFilter: value as ModelType | 'all' } });
  };

  const handleStatusFilterChange = (value: string) => {
    dispatch({ type: 'UPDATE_FILTERS', payload: { statusFilter: value as ModelStatus | 'all' } });
  };

  // 过滤模型
  const filteredModels = state.models.filter(model => {
    const matchesSearch = model.name.toLowerCase().includes(state.filters.searchTerm.toLowerCase()) ||
                         model.description.toLowerCase().includes(state.filters.searchTerm.toLowerCase());
    const matchesType = state.filters.typeFilter === 'all' || model.type === state.filters.typeFilter;
    const matchesStatus = state.filters.statusFilter === 'all' || model.status === state.filters.statusFilter;

    return matchesSearch && matchesType && matchesStatus;
  });

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">模型管理</h2>
          <p className="text-muted-foreground">管理和监控AI模型服务，配置参数模板</p>
        </div>
        <Button onClick={handleAddModel}>
          <Plus className="w-4 h-4 mr-2" />
          新增模型
        </Button>
      </div>

      {/* 4个统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-blue-600 dark:text-blue-400 font-medium">
                模型总数
              </div>
              <div className="text-2xl font-bold text-blue-700 dark:text-blue-300 mt-1">
                {state.totalModels}
              </div>
              <div className="text-xs text-blue-500 dark:text-blue-400 mt-1">
                当前系统中的模型数量
              </div>
            </div>
            <Brain className="w-8 h-8 text-blue-500 dark:text-blue-400" />
          </div>
        </Card>

        <Card className="p-4 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-green-600 dark:text-green-400 font-medium">
                运行中
              </div>
              <div className="text-2xl font-bold text-green-700 dark:text-green-300 mt-1">
                {state.runningModels}
              </div>
              <div className="text-xs text-green-500 dark:text-green-400 mt-1">
                正在提供服务的模型数量
              </div>
            </div>
            <PlayCircle className="w-8 h-8 text-green-500 dark:text-green-400" />
          </div>
        </Card>

        <Card className="p-4 bg-purple-50 dark:bg-purple-950 border-purple-200 dark:border-purple-800">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-purple-600 dark:text-purple-400 font-medium">
                平均准确率
              </div>
              <div className="text-2xl font-bold text-purple-700 dark:text-purple-300 mt-1">
                {state.avgAccuracy}%
              </div>
              <div className="text-xs text-purple-500 dark:text-purple-400 mt-1">
                所有模型的平均准确率
              </div>
            </div>
            <Target className="w-8 h-8 text-purple-500 dark:text-purple-400" />
          </div>
        </Card>

        <Card className="p-4 bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-orange-600 dark:text-orange-400 font-medium">
                QPS
              </div>
              <div className="text-2xl font-bold text-orange-700 dark:text-orange-300 mt-1">
                {state.qps}
              </div>
              <div className="text-xs text-orange-500 dark:text-orange-400 mt-1">
                每秒查询请求数
              </div>
            </div>
            <Zap className="w-8 h-8 text-orange-500 dark:text-orange-400" />
          </div>
        </Card>
      </div>

      {/* 模型服务管理功能介绍 */}
      <Card className="p-6 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
        <h3 className="text-lg font-semibold text-green-800 dark:text-green-200 mb-4">模型服务管理功能：</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div className="flex items-start space-x-3">
            <div className="w-2 h-2 rounded-full bg-green-500 mt-2 flex-shrink-0"></div>
            <div>
              <div className="font-medium text-green-800 dark:text-green-200">统一管理</div>
              <div className="text-sm text-green-600 dark:text-green-400">集中管理所有已注册的模型服务</div>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-2 h-2 rounded-full bg-green-500 mt-2 flex-shrink-0"></div>
            <div>
              <div className="font-medium text-green-800 dark:text-green-200">元信息维护</div>
              <div className="text-sm text-green-600 dark:text-green-400">模型描述、标签、版本等信息管理</div>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-2 h-2 rounded-full bg-green-500 mt-2 flex-shrink-0"></div>
            <div>
              <div className="font-medium text-green-800 dark:text-green-200">服务配置</div>
              <div className="text-sm text-green-600 dark:text-green-400">并发数、超时、重试等参数配置</div>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-2 h-2 rounded-full bg-green-500 mt-2 flex-shrink-0"></div>
            <div>
              <div className="font-medium text-green-800 dark:text-green-200">权限控制</div>
              <div className="text-sm text-green-600 dark:text-green-400">公开/私有/团队共享访问权限设置</div>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-2 h-2 rounded-full bg-green-500 mt-2 flex-shrink-0"></div>
            <div>
              <div className="font-medium text-green-800 dark:text-green-200">负载均衡</div>
              <div className="text-sm text-green-600 dark:text-green-400">自动负载均衡与弹性伸缩</div>
            </div>
          </div>
          <div className="flex items-start space-x-3">
            <div className="w-2 h-2 rounded-full bg-green-500 mt-2 flex-shrink-0"></div>
            <div>
              <div className="font-medium text-green-800 dark:text-green-200">高可用</div>
              <div className="text-sm text-green-600 dark:text-green-400">启停控制、性能监控、依赖管理</div>
            </div>
          </div>
        </div>
      </Card>

      {/* 搜索和筛选区域 */}
      <Card className="p-4">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1">
            <Label htmlFor="search">搜索模型</Label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
              <Input
                id="search"
                placeholder="搜索模型名称或描述..."
                value={state.filters.searchTerm}
                onChange={(e) => handleSearchChange(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>

          <div className="w-full md:w-48">
            <Label htmlFor="typeFilter">模型类型</Label>
            <Select value={state.filters.typeFilter} onValueChange={handleTypeFilterChange}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                <SelectItem value="pest_identification">病虫害识别</SelectItem>
                <SelectItem value="growth_status">生长状态</SelectItem>
                <SelectItem value="yield_prediction">产量预测</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="w-full md:w-48">
            <Label htmlFor="statusFilter">运行状态</Label>
            <Select value={state.filters.statusFilter} onValueChange={handleStatusFilterChange}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="active">运行中</SelectItem>
                <SelectItem value="inactive">已停止</SelectItem>
                <SelectItem value="testing">测试中</SelectItem>
                <SelectItem value="error">错误</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </Card>

      {/* 模型分析图表 */}
      <ModelAnalytics models={state.models} />

      {/* 模型服务列表 */}
      <ModelServiceList
        models={filteredModels}
        onEdit={handleEditModel}
        onView={handleViewModel}
        onDelete={handleDeleteModel}
        onToggle={handleToggleModel}
        onPermission={handlePermission}
        onPerformance={handlePerformance}
        onRedeploy={handleRedeploy}
        loading={state.loading}
      />

      {/* 新增模型对话框 */}
      <AddModelDialog
        open={state.showAddModelDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_ADD_MODEL_DIALOG', payload: open })}
        dispatch={dispatch}
      />

      {/* 权限管理对话框 */}
      <PermissionDialog
        open={state.showPermissionDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_PERMISSION_DIALOG', payload: open })}
        model={state.selectedModel}
      />

      {/* 性能调优对话框 */}
      <PerformanceDialog
        open={state.showPerformanceDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_PERFORMANCE_DIALOG', payload: open })}
        model={state.selectedModel}
      />

      {/* 重新部署对话框 */}
      <RedeployDialog
        open={state.showRedeployDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_REDEPLOY_DIALOG', payload: open })}
        model={state.selectedModel}
        dispatch={dispatch}
      />

      {/* 模型配置对话框 */}
      <ModelConfigDialog
        open={state.showConfigDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_CONFIG_DIALOG', payload: open })}
        model={state.selectedModel}
        dispatch={dispatch}
      />

      {/* 模型查看对话框 */}
      <ModelConfigDialog
        open={state.showViewDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_VIEW_DIALOG', payload: open })}
        model={state.selectedModel}
        viewMode={true}
        dispatch={dispatch}
      />

      {/* 删除确认对话框 */}
      <DeleteModelDialog
        open={state.showDeleteDialog}
        onOpenChange={(open) => dispatch({ type: 'SET_DELETE_DIALOG', payload: open })}
        model={state.selectedModel}
        dispatch={dispatch}
      />
    </div>
  );
}