import React, { useState, useEffect } from 'react';
import {
    Plus,
    Search,
    RotateCcw,
    Pencil,
    Trash2,
    Bell,
    BellOff,
    Rocket,
} from 'lucide-react';
import { Card, CardHeader, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { DataTablePagination } from '@/components/ui/pagination';
import type { SystemReleaseResponse } from './types';
import { ModuleType, ModuleTypeLabels } from './types';
import {
    getSystemReleaseList,
    deleteSystemRelease,
    markAsNotified,
    getUnnotifiedReleases,
} from './service';
import { ReleaseEditDialog } from './components/ReleaseEditDialog';
import dayjs from 'dayjs';

const SystemReleaseList: React.FC = () => {
    const { toast } = useToast();

    // 状态管理
    const [releases, setReleases] = useState<SystemReleaseResponse[]>([]);
    const [loading, setLoading] = useState(false);
    const [pageIndex, setPageIndex] = useState(0);
    const [pageSize] = useState(10);
    const [totalElements, setTotalElements] = useState(0);

    // 筛选条件
    const [searchVersion, setSearchVersion] = useState<string>('');
    const [selectedModule, setSelectedModule] = useState<string>('all');
    const [selectedNotified, setSelectedNotified] = useState<string>('all');

    // 对话框状态
    const [editDialogOpen, setEditDialogOpen] = useState(false);
    const [editingRelease, setEditingRelease] = useState<SystemReleaseResponse | null>(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [releaseToDelete, setReleaseToDelete] = useState<SystemReleaseResponse | null>(null);

    // 加载数据列表
    const loadReleases = async () => {
        setLoading(true);
        try {
            const params: any = {
                page: pageIndex,
                size: pageSize,
            };

            if (searchVersion) {
                params.releaseVersion = parseFloat(searchVersion);
            }
            if (selectedModule !== 'all') {
                params.module = selectedModule;
            }
            if (selectedNotified !== 'all') {
                params.notified = selectedNotified === 'true';
            }

            const result = await getSystemReleaseList(params);
            if (result) {
                setReleases(result.content || []);
                setTotalElements(result.totalElements || 0);
            }
        } catch (error) {
            console.error('加载系统版本列表失败:', error);
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '无法加载系统版本列表',
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadReleases();
    }, [pageIndex, pageSize]);

    // 搜索
    const handleSearch = () => {
        setPageIndex(0);
        loadReleases();
    };

    // 重置
    const handleReset = () => {
        setSearchVersion('');
        setSelectedModule('all');
        setSelectedNotified('all');
        setPageIndex(0);
        setTimeout(() => loadReleases(), 0);
    };

    // 新增
    const handleAdd = () => {
        setEditingRelease(null);
        setEditDialogOpen(true);
    };

    // 编辑
    const handleEdit = (release: SystemReleaseResponse) => {
        setEditingRelease(release);
        setEditDialogOpen(true);
    };

    // 删除
    const handleDelete = (release: SystemReleaseResponse) => {
        setReleaseToDelete(release);
        setDeleteDialogOpen(true);
    };

    const confirmDelete = async () => {
        if (!releaseToDelete) return;
        await deleteSystemRelease(releaseToDelete.id);
    };

    // 标记为已通知
    const handleMarkNotified = async (release: SystemReleaseResponse) => {
        try {
            await markAsNotified(release.id);
            toast({
                title: '操作成功',
                description: `版本 ${release.releaseVersion} 已标记为已通知`,
            });
            loadReleases();
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '操作失败',
                description: error.response?.data?.message || '无法标记为已通知',
            });
        }
    };

    // 查看未通知版本
    const handleViewUnnotified = async () => {
        try {
            const unnotified = await getUnnotifiedReleases();
            if (unnotified.length === 0) {
                toast({
                    title: '暂无未通知版本',
                    description: '所有版本都已发送通知',
                });
            } else {
                toast({
                    title: `未通知版本：${unnotified.length} 个`,
                    description: unnotified.map((r) => `v${r.releaseVersion}`).join(', '),
                });
            }
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '查询失败',
                description: '无法获取未通知版本列表',
            });
        }
    };

    // 成功回调
    const handleSuccess = () => {
        loadReleases();
    };

    // 页面变化
    const handlePageChange = (newPageIndex: number) => {
        setPageIndex(newPageIndex);
    };

    return (
        <div className="h-screen flex flex-col">
            {/* 顶部区域 */}
            <div className="flex-shrink-0 space-y-4 p-6">
                <div>
                    <h1 className="text-3xl font-bold flex items-center gap-2">
                        <Rocket className="h-8 w-8" />
                        系统版本管理
                    </h1>
                    <p className="text-muted-foreground mt-1">管理系统版本发布记录，支持版本信息的查询和维护</p>
                </div>
            </div>

            {/* 内容区域 */}
            <div className="flex-1 px-6 pb-6">
                <Card className="h-full flex flex-col">
                    {/* 搜索和操作栏 */}
                    <CardHeader className="flex-shrink-0">
                        <div className="space-y-4">
                            {/* 筛选栏 */}
                            <div className="flex items-center gap-3 flex-wrap">
                                <Input
                                    placeholder="搜索版本号..."
                                    value={searchVersion}
                                    onChange={(e) => setSearchVersion(e.target.value)}
                                    className="w-[200px]"
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                            handleSearch();
                                        }
                                    }}
                                />

                                <Select
                                    value={selectedModule}
                                    onValueChange={setSelectedModule}
                                >
                                    <SelectTrigger className="w-[140px]">
                                        <SelectValue placeholder="全部模块" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">全部模块</SelectItem>
                                        {Object.entries(ModuleTypeLabels).map(([key, value]) => (
                                            <SelectItem key={key} value={key}>
                                                {value.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>

                                <Select
                                    value={selectedNotified}
                                    onValueChange={setSelectedNotified}
                                >
                                    <SelectTrigger className="w-[140px]">
                                        <SelectValue placeholder="全部状态" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">全部状态</SelectItem>
                                        <SelectItem value="true">已通知</SelectItem>
                                        <SelectItem value="false">未通知</SelectItem>
                                    </SelectContent>
                                </Select>

                                <div className="flex gap-2 ml-auto">
                                    <Button variant="outline" size="sm" onClick={handleReset}>
                                        <RotateCcw className="h-4 w-4 mr-1.5" />
                                        重置
                                    </Button>
                                    <Button size="sm" onClick={handleSearch}>
                                        <Search className="h-4 w-4 mr-1.5" />
                                        查询
                                    </Button>
                                    <Button variant="outline" onClick={handleViewUnnotified}>
                                        <BellOff className="h-4 w-4 mr-2" />
                                        未通知版本
                                    </Button>
                                    <Button onClick={handleAdd}>
                                        <Plus className="h-4 w-4 mr-2" />
                                        新增版本
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </CardHeader>

                    <Separator className="flex-shrink-0" />

                    {/* 表格区域 */}
                    <CardContent className="flex-1 overflow-auto pt-6">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead width="100px">版本号</TableHead>
                                    <TableHead width="100px">模块类型</TableHead>
                                    <TableHead width="160px">发布时间</TableHead>
                                    <TableHead width="120px">维护配置</TableHead>
                                    <TableHead width="100px">通知状态</TableHead>
                                    <TableHead>变更内容</TableHead>
                                    <TableHead width="180px" className="text-right">操作</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading && releases.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-8">
                                            <span className="text-muted-foreground">加载中...</span>
                                        </TableCell>
                                    </TableRow>
                                ) : releases.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-8">
                                            <span className="text-muted-foreground">暂无数据</span>
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    releases.map((release) => (
                                        <TableRow key={release.id}>
                                            <TableCell>
                                                <span className="font-mono font-semibold">
                                                    v{release.releaseVersion}
                                                </span>
                                            </TableCell>
                                            <TableCell>
                                                <Badge
                                                    variant="outline"
                                                    className={`border-${ModuleTypeLabels[release.module].color}-500 text-${ModuleTypeLabels[release.module].color}-700 dark:text-${ModuleTypeLabels[release.module].color}-400`}
                                                >
                                                    {ModuleTypeLabels[release.module].label}
                                                </Badge>
                                            </TableCell>
                                            <TableCell>
                                                <span className="text-sm">
                                                    {dayjs(release.releaseDate).format('YYYY-MM-DD HH:mm:ss')}
                                                </span>
                                            </TableCell>
                                            <TableCell>
                                                {release.delayMinutes !== undefined && release.delayMinutes !== null ? (
                                                    <div className="text-xs space-y-1">
                                                        <div className="text-muted-foreground">
                                                            延迟: <span className="font-medium text-foreground">{release.delayMinutes}分钟</span>
                                                        </div>
                                                        {release.estimatedDuration && (
                                                            <div className="text-muted-foreground">
                                                                时长: <span className="font-medium text-foreground">{release.estimatedDuration}分钟</span>
                                                            </div>
                                                        )}
                                                        <div className="text-muted-foreground">
                                                            自动停服: <span className={`font-medium ${release.enableAutoShutdown ? 'text-red-600' : 'text-green-600'}`}>
                                                                {release.enableAutoShutdown ? '是' : '否'}
                                                            </span>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <span className="text-xs text-muted-foreground">-</span>
                                                )}
                                            </TableCell>
                                            <TableCell>
                                                {release.notified ? (
                                                    <Badge variant="outline" className="border-green-500 text-green-700 dark:text-green-400">
                                                        <Bell className="h-3 w-3 mr-1" />
                                                        已通知
                                                    </Badge>
                                                ) : (
                                                    <Badge variant="outline" className="border-gray-500 text-gray-700 dark:text-gray-400">
                                                        <BellOff className="h-3 w-3 mr-1" />
                                                        未通知
                                                    </Badge>
                                                )}
                                            </TableCell>
                                            <TableCell>
                                                <div className="max-w-md truncate text-sm text-muted-foreground">
                                                    {release.changes || '-'}
                                                </div>
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <div className="flex items-center justify-end gap-2">
                                                    {!release.notified && (
                                                        <Button
                                                            variant="ghost"
                                                            size="sm"
                                                            onClick={() => handleMarkNotified(release)}
                                                            className="h-8"
                                                        >
                                                            <Bell className="h-4 w-4 mr-1" />
                                                            标记通知
                                                        </Button>
                                                    )}
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() => handleEdit(release)}
                                                        className="h-8"
                                                    >
                                                        <Pencil className="h-4 w-4" />
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() => handleDelete(release)}
                                                        className="h-8 text-destructive hover:text-destructive"
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>

                        {/* 分页 */}
                        {!loading && releases.length > 0 && (
                            <div className="mt-4 flex items-center justify-between">
                                <div className="text-sm text-muted-foreground">
                                    共 {totalElements} 条记录，第 {pageIndex + 1} / {Math.ceil(totalElements / pageSize)} 页
                                </div>
                                <DataTablePagination
                                    pageIndex={pageIndex}
                                    pageSize={pageSize}
                                    pageCount={Math.ceil(totalElements / pageSize)}
                                    onPageChange={handlePageChange}
                                />
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* 编辑对话框 */}
            <ReleaseEditDialog
                open={editDialogOpen}
                onOpenChange={setEditDialogOpen}
                release={editingRelease}
                onSuccess={handleSuccess}
            />

            {/* 删除确认对话框 */}
            <ConfirmDialog
                open={deleteDialogOpen}
                onOpenChange={setDeleteDialogOpen}
                title="确认删除"
                description={`确定要删除版本"v${releaseToDelete?.releaseVersion}"吗？此操作无法撤销。`}
                item={releaseToDelete}
                onConfirm={confirmDelete}
                onSuccess={() => {
                    toast({
                        title: '删除成功',
                        description: `版本"v${releaseToDelete?.releaseVersion}"已删除`,
                    });
                    setReleaseToDelete(null);
                    loadReleases();
                }}
                variant="destructive"
                confirmText="确定"
            />
        </div>
    );
};

export default SystemReleaseList;
