import React, { useState, useEffect, useRef, useMemo } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import {
  CodeOutlined,
  JavaOutlined,
  NodeIndexOutlined,
  PythonOutlined,
} from '@ant-design/icons';
import { getApplicationPage } from './service';
import type { Application, ApplicationQuery } from './types';
import { DevelopmentLanguageTypeEnum } from './types';
import { getEnabledCategories } from '../Category/service';
import type { ApplicationCategoryResponse } from '../Category/types';
import ApplicationModal from './components/ApplicationModal';
import DeleteDialog from './components/DeleteDialog';
import CategoryManageDialog from './components/CategoryManageDialog';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import { Plus, Edit, Trash2, Server, Activity, Database, Settings } from 'lucide-react';

// 获取开发语言信息
const getLanguageInfo = (language: DevelopmentLanguageTypeEnum) => {
  switch (language) {
    case DevelopmentLanguageTypeEnum.JAVA:
      return { label: 'Java', icon: <JavaOutlined />, color: '#E76F00' };
    case DevelopmentLanguageTypeEnum.NODE_JS:
      return { label: 'NodeJS', icon: <NodeIndexOutlined />, color: '#339933' };
    case DevelopmentLanguageTypeEnum.PYTHON:
      return { label: 'Python', icon: <PythonOutlined />, color: '#3776AB' };
    case DevelopmentLanguageTypeEnum.GO:
      return { label: 'Go', icon: <CodeOutlined />, color: '#00ADD8' };
    default:
      return { label: language || '未知', icon: <CodeOutlined />, color: '#666666' };
  }
};

const ApplicationList: React.FC = () => {
  const tableRef = useRef<PaginatedTableRef<Application>>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [categoryDialogOpen, setCategoryDialogOpen] = useState(false);
  const [currentApplication, setCurrentApplication] = useState<Application>();
  const [categories, setCategories] = useState<ApplicationCategoryResponse[]>([]);
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });

  // 加载分类列表
  const loadCategories = async () => {
    try {
      const data = await getEnabledCategories();
      setCategories(data || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  useEffect(() => {
    loadCategories();
  }, []);

  // 包装 fetchFn，同时更新统计数据
  const fetchData = async (query: ApplicationQuery) => {
    const result = await getApplicationPage(query);
    // 更新统计
    const all = result.content || [];
    setStats({
      total: all.length,
      enabled: all.filter((item) => item.enabled).length,
      disabled: all.filter((item) => !item.enabled).length,
    });
    return result;
  };

  const handleAdd = () => {
    setCurrentApplication(undefined);
    setModalVisible(true);
  };

  const handleEdit = (application: Application) => {
    setCurrentApplication(application);
    setModalVisible(true);
  };

  const handleModalClose = () => {
    setModalVisible(false);
    setCurrentApplication(undefined);
  };

  const handleSuccess = () => {
    setModalVisible(false);
    setCurrentApplication(undefined);
    tableRef.current?.refresh();
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'appCode', type: 'input', placeholder: '应用编码', width: 'w-[180px]' },
    { key: 'appName', type: 'input', placeholder: '应用名称', width: 'w-[180px]' },
    {
      key: 'applicationCategoryId',
      type: 'select',
      placeholder: '全部分类',
      width: 'w-[180px]',
      options: categories.map(c => ({ label: c.name, value: c.id })),
    },
    {
      key: 'language',
      type: 'select',
      placeholder: '开发语言',
      width: 'w-[150px]',
      options: [
        { label: 'Java', value: DevelopmentLanguageTypeEnum.JAVA },
        { label: 'NodeJS', value: DevelopmentLanguageTypeEnum.NODE_JS },
        { label: 'Python', value: DevelopmentLanguageTypeEnum.PYTHON },
        { label: 'Go', value: DevelopmentLanguageTypeEnum.GO },
      ],
    },
    {
      key: 'enabled',
      type: 'select',
      placeholder: '状态',
      width: 'w-[120px]',
      options: [
        { label: '启用', value: 'true' },
        { label: '禁用', value: 'false' },
      ],
    },
  ], [categories]);

  // 列定义
  const columns: ColumnDef<Application>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    {
      key: 'category',
      title: '应用分类',
      width: '100px',
      className: 'whitespace-nowrap',
      render: (_, record) => record.applicationCategory?.name || '-',
    },
    { key: 'appCode', title: '应用编码', dataIndex: 'appCode', width: '220px', className: 'whitespace-nowrap' },
    { key: 'appName', title: '应用名称', dataIndex: 'appName', width: '180px', className: 'whitespace-nowrap' },
    { 
      key: 'appDesc', 
      title: '应用描述', 
      width: '200px', 
      className: 'whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]',
      render: (_, record) => (
        <div className="whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]" title={record.appDesc || ''}>
          {record.appDesc || '-'}
        </div>
      ),
    },
    {
      key: 'teamCount',
      title: '团队使用数量',
      width: '100px',
      className: 'whitespace-nowrap',
      render: (_, record) => (
        <div className="text-center">
          <span className="font-medium">{record.teamCount || 0}</span>
        </div>
      ),
    },
    {
      key: 'language',
      title: '开发语言',
      width: '100px',
      className: 'whitespace-nowrap',
      render: (_, record) => {
        const langInfo = getLanguageInfo(record.language);
        return (
          <Badge variant="outline" className="flex items-center gap-1 inline-flex whitespace-nowrap">
            {langInfo.icon}
            {langInfo.label}
          </Badge>
        );
      },
    },
    {
      key: 'enabled',
      title: '状态',
      width: '70px',
      className: 'whitespace-nowrap',
      render: (_, record) => (
        <Badge variant={record.enabled ? 'default' : 'secondary'} className="inline-flex whitespace-nowrap">
          {record.enabled ? '启用' : '禁用'}
        </Badge>
      ),
    },
    { key: 'sort', title: '排序', dataIndex: 'sort', width: '60px', className: 'whitespace-nowrap' },
    {
      key: 'actions',
      title: '操作',
      width: '140px',
      sticky: true,
      className: 'whitespace-nowrap',
      render: (_, record) => (
        <div className="flex items-center gap-2 whitespace-nowrap">
          <Button variant="ghost" size="sm" onClick={() => handleEdit(record)}>
            <Edit className="h-4 w-4 mr-1" />编辑
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setCurrentApplication(record);
              setDeleteDialogOpen(true);
            }}
            className="text-destructive hover:text-destructive"
          >
            <Trash2 className="h-4 w-4 mr-1" />删除
          </Button>
        </div>
      ),
    },
  ], []);

  // 工具栏
  const toolbar = (
    <>
      <Button variant="outline" onClick={() => setCategoryDialogOpen(true)}>
        <Settings className="h-4 w-4 mr-2" />分类管理
      </Button>
      <Button onClick={handleAdd}>
        <Plus className="h-4 w-4 mr-2" />新建应用
      </Button>
    </>
  );

  return (
    <PageContainer>
      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总应用数</CardTitle>
            <Server className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">所有应用</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已启用</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.enabled}</div>
            <p className="text-xs text-muted-foreground">正在使用中</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已禁用</CardTitle>
            <Database className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-gray-600">{stats.disabled}</div>
            <p className="text-xs text-muted-foreground">暂时停用</p>
          </CardContent>
        </Card>
      </div>

      {/* 应用管理 */}
      <Card>
        <CardHeader>
          <div>
            <CardTitle>应用管理</CardTitle>
            <CardDescription className="mt-2">
              创建和管理应用，支持Git集成和分类管理
            </CardDescription>
          </div>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<Application, ApplicationQuery>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1400px"
          />
        </CardContent>
      </Card>

      {/* 对话框 */}
      {modalVisible && (
        <ApplicationModal
          open={modalVisible}
          onCancel={handleModalClose}
          onSuccess={handleSuccess}
          initialValues={currentApplication}
        />
      )}
      <DeleteDialog
        open={deleteDialogOpen}
        record={currentApplication}
        onOpenChange={setDeleteDialogOpen}
        onSuccess={handleSuccess}
      />
      <CategoryManageDialog
        open={categoryDialogOpen}
        onOpenChange={setCategoryDialogOpen}
        onSuccess={loadCategories}
      />
    </PageContainer>
  );
};

export default ApplicationList;
