import React, { useState, useMemo, useRef } from 'react';
import { PageContainer } from '@/components/ui/page-container';
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { PaginatedTable, type ColumnDef, type SearchFieldDef, type PaginatedTableRef } from '@/components/ui/paginated-table';
import { Plus, Edit, Trash2, Server, Activity, Database } from 'lucide-react';
import EditDialog from './components/EditDialog';
import DeleteDialog from './components/DeleteDialog';
import { getEnvironmentPage } from './service';
import type { Environment, EnvironmentQueryParams } from './types';

const EnvironmentList: React.FC = () => {
  const tableRef = useRef<PaginatedTableRef<Environment>>(null);
  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>();

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

  const handleAdd = () => {
    setCurrentRecord(undefined);
    setEditDialogOpen(true);
  };

  const handleEdit = (environment: Environment) => {
    setCurrentRecord(environment);
    setEditDialogOpen(true);
  };

  const handleSuccess = () => {
    setEditDialogOpen(false);
    setDeleteDialogOpen(false);
    setCurrentRecord(undefined);
    tableRef.current?.refresh();
  };

  // 搜索字段定义
  const searchFields: SearchFieldDef[] = useMemo(() => [
    { key: 'envCode', type: 'input', placeholder: '环境编码', width: 'w-[180px]' },
    { key: 'envName', type: 'input', placeholder: '环境名称', width: 'w-[180px]' },
    {
      key: 'enabled',
      type: 'select',
      placeholder: '状态',
      width: 'w-[120px]',
      options: [
        { label: '启用', value: 'true' },
        { label: '禁用', value: 'false' },
      ],
    },
  ], []);

  // 列定义
  const columns: ColumnDef<Environment>[] = useMemo(() => [
    { key: 'id', title: 'ID', dataIndex: 'id', width: '80px' },
    { key: 'envCode', title: '环境编码', dataIndex: 'envCode', width: '150px' },
    { key: 'envName', title: '环境名称', dataIndex: 'envName', width: '150px' },
    { 
      key: 'envDesc', 
      title: '环境描述', 
      width: '200px',
      render: (_, record) => (
        <div className="truncate max-w-[200px]" title={record.envDesc || ''}>
          {record.envDesc || '-'}
        </div>
      ),
    },
    { key: 'teamCount', title: '团队数', dataIndex: 'teamCount', width: '100px' },
    { key: 'applicationCount', title: '应用数', dataIndex: 'applicationCount', width: '100px' },
    {
      key: 'enabled',
      title: '状态',
      width: '100px',
      render: (_, record) => (
        <Badge variant={record.enabled ? 'default' : 'secondary'}>
          {record.enabled ? '启用' : '禁用'}
        </Badge>
      ),
    },
    { key: 'sort', title: '排序', dataIndex: 'sort', width: '80px' },
    {
      key: 'actions',
      title: '操作',
      width: '160px',
      sticky: true,
      render: (_, record) => (
        <div className="flex items-center gap-2">
          <Button variant="ghost" size="sm" onClick={() => handleEdit(record)}>
            <Edit className="h-4 w-4 mr-1" />编辑
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setCurrentRecord(record);
              setDeleteDialogOpen(true);
            }}
            className="text-destructive hover:text-destructive"
          >
            <Trash2 className="h-4 w-4 mr-1" />删除
          </Button>
        </div>
      ),
    },
  ], []);

  // 工具栏
  const toolbar = (
    <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">
              创建和管理部署环境，配置环境参数
            </CardDescription>
          </div>
        </CardHeader>
        <Separator />
        <CardContent className="pt-6">
          <PaginatedTable<Environment, EnvironmentQueryParams>
            ref={tableRef}
            fetchFn={fetchData}
            columns={columns}
            searchFields={searchFields}
            toolbar={toolbar}
            rowKey="id"
            minWidth="1200px"
          />
        </CardContent>
      </Card>

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

export default EnvironmentList;
