import React, { useState, useEffect } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { DataTablePagination } from '@/components/ui/pagination';
import { Plus, Edit, Trash2, Server, Activity, Database } from 'lucide-react';
import EditDialog from './components/EditDialog';
import DeleteDialog from './components/DeleteDialog';
import { getEnvironmentPage, deleteEnvironment } from './service';
import type { Environment, EnvironmentQueryParams, BuildTypeEnum, DeployTypeEnum } from './types';
import { getBuildTypeInfo, getDeployTypeInfo } from './utils';

const DEFAULT_PAGE_SIZE = 10;

const EnvironmentList: React.FC = () => {
  const { toast } = useToast();
  const [list, setList] = useState<Environment[]>([]);
  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState<EnvironmentQueryParams>({
    pageNum: 1,
    pageSize: DEFAULT_PAGE_SIZE,
  });
  const [total, setTotal] = useState(0);
  const [stats, setStats] = useState({ total: 0, enabled: 0, disabled: 0 });

  // 对话框状态
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<Environment>();

  // 加载数据
  const loadData = async () => {
    setLoading(true);
    try {
      const response = await getEnvironmentPage(query);
      if (response) {
        setList(response.content || []);
        setTotal(response.totalElements || 0);
        // 计算统计数据
        const all = response.content || [];
        setStats({
          total: all.length,
          enabled: all.filter((item) => item.enabled).length,
          disabled: all.filter((item) => !item.enabled).length,
        });
      }
    } catch (error) {
      toast({ title: '加载失败', description: '无法加载环境列表', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [query.pageNum, query.pageSize]);

  // 搜索
  const handleSearch = () => {
    setQuery({ ...query, pageNum: 1 });
    loadData();
  };

  // 重置
  const handleReset = () => {
    setQuery({ pageNum: 1, pageSize: DEFAULT_PAGE_SIZE });
    loadData();
  };

  return (
    <PageContainer>
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold tracking-tight">环境管理</h2>
        <Button onClick={() => {
          setCurrentRecord(undefined);
          setEditDialogOpen(true);
        }}>
          <Plus className="h-4 w-4 mr-2" />
          新建环境
        </Button>
      </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={query.envCode || ''}
              onChange={(e) => setQuery({ ...query, envCode: e.target.value })}
              className="max-w-[200px]"
            />
            <Input
              placeholder="环境名称"
              value={query.envName || ''}
              onChange={(e) => setQuery({ ...query, envName: e.target.value })}
              className="max-w-[200px]"
            />
            <Select
              value={query.buildType}
              onValueChange={(value) => setQuery({ ...query, buildType: value as BuildTypeEnum })}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="构建类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="JENKINS">Jenkins构建</SelectItem>
                <SelectItem value="GITLAB_RUNNER">GitLab Runner构建</SelectItem>
                <SelectItem value="GITHUB_ACTION">GitHub Action构建</SelectItem>
              </SelectContent>
            </Select>
            <Select
              value={query.deployType}
              onValueChange={(value) => setQuery({ ...query, deployType: value as DeployTypeEnum })}
            >
              <SelectTrigger className="max-w-[200px]">
                <SelectValue placeholder="部署类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="K8S">Kubernetes集群部署</SelectItem>
                <SelectItem value="DOCKER">Docker容器部署</SelectItem>
                <SelectItem value="VM">虚拟机部署</SelectItem>
              </SelectContent>
            </Select>
            <Button variant="outline" onClick={handleReset}>
              重置
            </Button>
            <Button onClick={handleSearch}>
              搜索
            </Button>
          </div>
        </div>
      </Card>

      {/* 数据表格 */}
      <Card>
        <CardHeader>
          <CardTitle>环境列表</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[120px]">环境编码</TableHead>
                  <TableHead className="w-[150px]">环境名称</TableHead>
                  <TableHead className="w-[200px]">环境描述</TableHead>
                  <TableHead className="w-[150px]">构建类型</TableHead>
                  <TableHead className="w-[150px]">部署类型</TableHead>
                  <TableHead className="w-[80px]">排序</TableHead>
                  <TableHead className="w-[100px]">状态</TableHead>
                  <TableHead className="w-[200px]">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {list.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="h-24 text-center">
                      暂无数据
                    </TableCell>
                  </TableRow>
                ) : (
                  list.map((item) => {
                    const buildInfo = getBuildTypeInfo(item.buildType);
                    const deployInfo = getDeployTypeInfo(item.deployType);
                    return (
                      <TableRow key={item.id}>
                        <TableCell className="font-medium">{item.envCode}</TableCell>
                        <TableCell>{item.envName}</TableCell>
                        <TableCell className="text-muted-foreground">{item.envDesc || '-'}</TableCell>
                        <TableCell>
                          <Badge variant="outline" className="inline-flex items-center gap-1">
                            {buildInfo.icon}
                            {buildInfo.label}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="secondary" className="inline-flex items-center gap-1">
                            {deployInfo.icon}
                            {deployInfo.label}
                          </Badge>
                        </TableCell>
                        <TableCell>{item.sort}</TableCell>
                        <TableCell>
                          <Badge variant={item.enabled ? "default" : "secondary"} className="inline-flex">
                            {item.enabled ? '启用' : '禁用'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setCurrentRecord(item);
                                setEditDialogOpen(true);
                              }}
                            >
                              <Edit className="h-4 w-4 mr-1" />
                              编辑
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => {
                                setCurrentRecord(item);
                                setDeleteDialogOpen(true);
                              }}
                              className="text-destructive hover:text-destructive"
                            >
                              <Trash2 className="h-4 w-4 mr-1" />
                              删除
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
            <div className="flex justify-end border-t border-border bg-muted/40">
              <DataTablePagination
                pageIndex={query.pageNum || 1}
                pageSize={query.pageSize || DEFAULT_PAGE_SIZE}
                pageCount={Math.ceil(total / (query.pageSize || DEFAULT_PAGE_SIZE))}
                onPageChange={(page) => setQuery({ ...query, pageNum: page })}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 对话框 */}
      <EditDialog
        open={editDialogOpen}
        record={currentRecord}
        onOpenChange={setEditDialogOpen}
        onSuccess={loadData}
      />
      <DeleteDialog
        open={deleteDialogOpen}
        record={currentRecord}
        onOpenChange={setDeleteDialogOpen}
        onSuccess={loadData}
      />
    </PageContainer>
  );
};

export default EnvironmentList;
