import React, { useState, useEffect } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CodeOutlined,
  GithubOutlined,
  JavaOutlined,
  NodeIndexOutlined,
  PythonOutlined,
} from '@ant-design/icons';
import { getApplicationPage, deleteApplication } from './service';
import { getProjectGroupList } from '../../ProjectGroup/List/service';
import type { Application, ApplicationQuery } from './types';
import { DevelopmentLanguageTypeEnum } from './types';
import type { ProjectGroup } from '../../ProjectGroup/List/types';
import ApplicationModal from './components/ApplicationModal';
import DeleteDialog from './components/DeleteDialog';
import {
  Table,
  TableHeader,
  TableBody,
  TableHead,
  TableRow,
  TableCell,
} from '@/components/ui/table';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { searchFormSchema, type SearchFormValues } from './schema';
import { DataTablePagination } from '@/components/ui/pagination';
import { Plus, Edit, Trash2, Server, Activity, Database, ExternalLink } from 'lucide-react';

interface Column {
  accessorKey?: keyof Application;
  id?: string;
  header: string;
  size: number;
  cell?: (props: { row: { original: Application } }) => React.ReactNode;
}

const DEFAULT_PAGE_SIZE = 10;

const ApplicationList: React.FC = () => {
  const [projectGroups, setProjects] = useState<ProjectGroup[]>([]);
  const [selectedProjectGroupId, setSelectedProjectGroupId] = useState<number>();
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [currentApplication, setCurrentApplication] = useState<Application>();
  const [list, setList] = useState<Application[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    totalElements: 0,
  });
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });
  const { toast } = useToast();

  const form = useForm<SearchFormValues>({
    resolver: zodResolver(searchFormSchema),
    defaultValues: {
      appCode: '',
      appName: '',
      language: undefined,
      enabled: undefined,
    },
  });

  // 获取项目列表
  const fetchProjects = async () => {
    try {
      const data = await getProjectGroupList();
      setProjects(data);
      if (data.length > 0 && !selectedProjectGroupId) {
        setSelectedProjectGroupId(data[0].id);
      }
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '获取项目组列表失败',
        duration: 3000,
      });
    }
  };

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

  const loadData = async (params?: ApplicationQuery) => {
    if (!selectedProjectGroupId) {
      setList([]);
      return;
    }
    setLoading(true);
    try {
      const queryParams: ApplicationQuery = {
        ...params,
        projectGroupId: selectedProjectGroupId,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
      };
      const data = await getApplicationPage(queryParams);
      setList(data.content || []);
      setPagination({
        ...pagination,
        totalElements: data.totalElements,
      });
      // 计算统计数据
      const all = data.content || [];
      setStats({
        total: all.length,
        enabled: all.filter((item) => item.enabled).length,
        disabled: all.filter((item) => !item.enabled).length,
      });
    } catch (error) {
      toast({
        variant: 'destructive',
        title: '获取应用列表失败',
        duration: 3000,
      });
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (page: number) => {
    setPagination({
      ...pagination,
      pageNum: page,
    });
  };

  useEffect(() => {
    loadData(form.getValues());
  }, [selectedProjectGroupId, pagination.pageNum, pagination.pageSize]);

  const handleAdd = () => {
    if (!selectedProjectGroupId) {
      toast({
        variant: 'destructive',
        title: '请先选择项目组',
        duration: 3000,
      });
      return;
    }
    setCurrentApplication(undefined);
    setModalVisible(true);
  };

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

  const handleProjectChange = (value: string) => {
    setSelectedProjectGroupId(Number(value));
  };

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

  const handleSuccess = () => {
    setModalVisible(false);
    setCurrentApplication(undefined);
    loadData(form.getValues());
  };

  // 获取开发语言信息
  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 columns: Column[] = [
    {
      accessorKey: 'appCode',
      header: '应用编码',
      size: 180,
    },
    {
      accessorKey: 'appName',
      header: '应用名称',
      size: 150,
    },
    {
      id: 'projectGroup',
      header: '项目组',
      size: 150,
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <span>{row.original.projectGroup?.projectGroupName}</span>
        </div>
      ),
    },
    {
      accessorKey: 'appDesc',
      header: '应用描述',
      size: 200,
    },
    {
      id: 'externalSystem',
      header: '外部系统',
      size: 150,
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <span>{row.original.externalSystem?.name || '-'}</span>
        </div>
      ),
    },
    {
      id: 'repository',
      header: '代码仓库',
      size: 200,
      cell: ({ row }) => {
        const project = row.original.repositoryProject;
        return project ? (
          <div className="flex items-center gap-2">
            <GithubOutlined />
            <a
              href={project.webUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-500 hover:text-blue-700 flex items-center gap-1"
            >
              {project.name}
              <ExternalLink className="h-3 w-3" />
            </a>
          </div>
        ) : (
          '-'
        );
      },
    },
    {
      accessorKey: 'language',
      header: '开发语言',
      size: 120,
      cell: ({ row }) => {
        const langInfo = getLanguageInfo(row.original.language);
        return (
          <Badge variant="outline" className="flex items-center gap-1 inline-flex">
            {langInfo.icon}
            {langInfo.label}
          </Badge>
        );
      },
    },
    {
      accessorKey: 'enabled',
      header: '状态',
      size: 100,
      cell: ({ row }) => (
        <Badge variant={row.original.enabled ? 'default' : 'secondary'} className="inline-flex">
          {row.original.enabled ? '启用' : '禁用'}
        </Badge>
      ),
    },
    {
      accessorKey: 'sort',
      header: '排序',
      size: 80,
    },
    {
      id: 'actions',
      header: '操作',
      size: 180,
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="sm" onClick={() => handleEdit(row.original)}>
            <Edit className="h-4 w-4 mr-1" />
            编辑
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setCurrentApplication(row.original);
              setDeleteDialogOpen(true);
            }}
            className="text-destructive hover:text-destructive"
          >
            <Trash2 className="h-4 w-4 mr-1" />
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <PageContainer>
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold tracking-tight">应用管理</h2>
        <div className="flex items-center gap-4">
          <Select
            value={selectedProjectGroupId?.toString()}
            onValueChange={handleProjectChange}
          >
            <SelectTrigger className="w-[200px]">
              <SelectValue placeholder="请选择项目组" />
            </SelectTrigger>
            <SelectContent>
              {projectGroups.map((project) => (
                <SelectItem key={project.id} value={project.id.toString()}>
                  {project.projectGroupName}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button onClick={handleAdd} disabled={!selectedProjectGroupId}>
            <Plus className="h-4 w-4 mr-2" />
            新建应用
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <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>
        <div className="p-6">
          <div className="flex items-center gap-4">
            <Input
              placeholder="应用编码"
              value={form.watch('appCode')}
              onChange={(e) => form.setValue('appCode', e.target.value)}
              className="max-w-[200px]"
            />
            <Input
              placeholder="应用名称"
              value={form.watch('appName')}
              onChange={(e) => form.setValue('appName', e.target.value)}
              className="max-w-[200px]"
            />
            <Select
              value={form.watch('language')}
              onValueChange={(value) =>
                form.setValue('language', value as DevelopmentLanguageTypeEnum)
              }
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="开发语言" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={DevelopmentLanguageTypeEnum.JAVA}>Java</SelectItem>
                <SelectItem value={DevelopmentLanguageTypeEnum.NODE_JS}>NodeJS</SelectItem>
                <SelectItem value={DevelopmentLanguageTypeEnum.PYTHON}>Python</SelectItem>
                <SelectItem value={DevelopmentLanguageTypeEnum.GO}>Go</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={form.watch('enabled')?.toString()}
              onValueChange={(value) => form.setValue('enabled', value === 'true')}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="true">启用</SelectItem>
                <SelectItem value="false">禁用</SelectItem>
              </SelectContent>
            </Select>
            <Button variant="outline" onClick={() => form.reset()}>
              重置
            </Button>
            <Button onClick={() => loadData(form.getValues())}>搜索</Button>
          </div>
        </div>
      </Card>

      {/* 数据表格 */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>应用列表</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  {columns.map((column) => (
                    <TableHead
                      key={column.accessorKey || column.id}
                      style={{ width: column.size }}
                    >
                      {column.header}
                    </TableHead>
                  ))}
                </TableRow>
              </TableHeader>
              <TableBody>
                {list.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={columns.length} className="h-24 text-center">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  list.map((item) => (
                    <TableRow key={item.id}>
                      {columns.map((column) => (
                        <TableCell key={column.accessorKey || column.id}>
                          {column.cell
                            ? column.cell({ row: { original: item } })
                            : item[column.accessorKey!]}
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
            <div className="flex justify-end border-t border-border bg-muted/40">
              <DataTablePagination
                pageIndex={pagination.pageNum}
                pageSize={pagination.pageSize}
                pageCount={Math.ceil(pagination.totalElements / pagination.pageSize)}
                onPageChange={handlePageChange}
              />
            </div>
          </div>
        </CardContent>
      </Card>

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

export default ApplicationList;
