import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
} from '@/components/ui/table';
import { useToast } from '@/components/ui/use-toast';
import { Plus, Edit, Trash2, Loader2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { DataTablePagination } from '@/components/ui/pagination';
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NUM } from '@/utils/page';
import type { MenuResponse } from '../types';
import {
  getPermissions,
  createPermission,
  updatePermission,
  deletePermission,
} from '@/pages/System/Permission/List/service';
import type {
  PermissionResponse,
  PermissionRequest,
} from '@/pages/System/Permission/List/types';
import PermissionEditDialog, { type FormValues } from './PermissionEditDialog';

interface PermissionDialogProps {
  open: boolean;
  menu: MenuResponse;
  onOpenChange: (open: boolean) => void;
}

const PermissionDialog: React.FC<PermissionDialogProps> = ({
  open,
  menu,
  onOpenChange,
}) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [permissions, setPermissions] = useState<PermissionResponse[]>([]);
  const [pagination, setPagination] = useState({
    pageNum: DEFAULT_PAGE_NUM,
    pageSize: DEFAULT_PAGE_SIZE,
    totalElements: 0,
  });
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<PermissionResponse | undefined>();

  // 加载权限列表
  const loadPermissions = async () => {
    setLoading(true);
    try {
      const response = await getPermissions({
        menuId: menu.id,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
      });
      if (response) {
        setPermissions(response.content || []);
        setPagination({
          ...pagination,
          totalElements: response.totalElements || 0,
        });
      }
    } catch (error) {
      console.error('加载权限失败:', error);
      toast({
        title: '加载失败',
        description: '获取权限列表失败',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      // 每次打开都重置到初始状态
      setPagination({
        pageNum: DEFAULT_PAGE_NUM,
        pageSize: DEFAULT_PAGE_SIZE,
        totalElements: 0,
      });
      setPermissions([]);
      setEditDialogOpen(false);
      setEditRecord(undefined);
    }
  }, [open, menu.id]);

  useEffect(() => {
    if (open) {
      loadPermissions();
    }
  }, [open, pagination.pageNum, pagination.pageSize]);

  // 新增
  const handleAdd = () => {
    setEditRecord(undefined);
    setEditDialogOpen(true);
  };

  // 编辑
  const handleEdit = (record: PermissionResponse) => {
    setEditRecord(record);
    setEditDialogOpen(true);
  };

  // 提交表单
  const handleFormSubmit = async (formData: FormValues) => {
    try {
      const data: PermissionRequest = {
        menuId: menu.id,
        code: formData.code,
        name: formData.name,
        type: formData.type,
        sort: formData.sort,
      };

      if (editRecord) {
        await updatePermission(editRecord.id, data);
        toast({
          title: '更新成功',
          description: `权限 "${formData.name}" 已更新`,
        });
      } else {
        await createPermission(data);
        toast({
          title: '创建成功',
          description: `权限 "${formData.name}" 已创建`,
        });
      }

      setEditDialogOpen(false);

      // 保存后重置分页到第一页
      if (!editRecord && pagination.pageNum !== 0) {
        setPagination({ ...pagination, pageNum: 0 });
      } else {
        loadPermissions();
      }
    } catch (error: any) {
      toast({
        title: editRecord ? '更新失败' : '创建失败',
        description: error.response?.data?.message || '操作失败',
        variant: 'destructive',
      });
    }
  };

  // 删除
  const handleDelete = async (record: PermissionResponse) => {
    if (!confirm(`确定要删除权限 "${record.name}" 吗?`)) return;

    try {
      await deletePermission(record.id);
      toast({
        title: '删除成功',
        description: `权限 "${record.name}" 已删除`,
      });
      loadPermissions();
    } catch (error: any) {
      toast({
        title: '删除失败',
        description: error.response?.data?.message || '删除失败',
        variant: 'destructive',
      });
    }
  };

  // 获取权限类型Badge
  const getTypeBadge = (type: string) => {
    const typeMap: Record<
      string,
      { text: string; variant: 'default' | 'secondary' | 'outline' }
    > = {
      MENU: { text: '菜单', variant: 'default' },
      BUTTON: { text: '按钮', variant: 'secondary' },
      API: { text: '接口', variant: 'outline' },
    };
    const info = typeMap[type] || { text: type, variant: 'outline' };
    return <Badge variant={info.variant}>{info.text}</Badge>;
  };

  // 分页变化
  const handlePageChange = (newPage: number) => {
    setPagination({ ...pagination, pageNum: newPage + 1 });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl">
        <DialogHeader>
          <DialogTitle>权限管理：{menu.name}</DialogTitle>
          <p className="text-sm text-muted-foreground mt-1">
            管理该菜单下的权限点
          </p>
        </DialogHeader>

        <DialogBody>
          {/* 权限列表 */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="font-medium">权限列表</h3>
              <Button size="sm" onClick={handleAdd}>
                <Plus className="h-4 w-4 mr-1" />
                新增权限
              </Button>
            </div>

            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead width="200px">权限编码</TableHead>
                    <TableHead width="150px">权限名称</TableHead>
                    <TableHead width="100px">类型</TableHead>
                    <TableHead width="80px" className="text-center">
                      排序
                    </TableHead>
                    <TableHead width="120px" className="text-right">
                      操作
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    <TableRow>
                      <TableCell colSpan={5} className="h-24 text-center">
                        <div className="flex items-center justify-center">
                          <Loader2 className="h-6 w-6 animate-spin mr-2" />
                          <span className="text-sm text-muted-foreground">
                            加载中...
                          </span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : permissions.length > 0 ? (
                    permissions.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell width="200px">
                          <code className="text-xs bg-muted px-2 py-0.5 rounded">
                            {item.code}
                          </code>
                        </TableCell>
                        <TableCell width="150px" className="font-medium">
                          {item.name}
                        </TableCell>
                        <TableCell width="100px">
                          {getTypeBadge(item.type)}
                        </TableCell>
                        <TableCell width="80px" className="text-center">
                          {item.sort}
                        </TableCell>
                        <TableCell width="120px" className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(item)}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDelete(item)}
                              className="text-destructive hover:text-destructive"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={5} className="h-24 text-center">
                        <div className="text-sm text-muted-foreground">
                          暂无权限数据
                        </div>
                      </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>
          </div>
        </DialogBody>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            关闭
          </Button>
        </DialogFooter>
      </DialogContent>

      {/* 编辑对话框 */}
      <PermissionEditDialog
        open={editDialogOpen}
        record={editRecord}
        menuId={menu.id}
        menuName={menu.name}
        onOpenChange={setEditDialogOpen}
        onSubmit={handleFormSubmit}
      />
    </Dialog>
  );
};

export default PermissionDialog;

