import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { HelpCircle } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { createMenu, updateMenu } from '../service';
import type { MenuResponse, MenuRequest, MenuTypeEnum } from '../types';
import IconSelect from '@/components/IconSelect';
import { getIconComponent } from '@/config/icons.tsx';

interface EditDialogProps {
  open: boolean;
  record?: MenuResponse;
  menuTree: MenuResponse[];
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

/**
 * 菜单编辑对话框
 */
const EditDialog: React.FC<EditDialogProps> = ({
  open,
  record,
  menuTree,
  onOpenChange,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [iconSelectVisible, setIconSelectVisible] = useState(false);
  const [formData, setFormData] = useState<Partial<MenuRequest>>({
    type: 2, // 默认菜单类型
    sort: 1,
    hidden: false,
  });

  useEffect(() => {
    if (open) {
      if (record) {
        setFormData({
          name: record.name,
          type: record.type,
          parentId: record.parentId === 0 ? undefined : record.parentId,
          path: record.path,
          component: record.component,
          permission: record.permission,
          icon: record.icon,
          sort: record.sort,
          hidden: record.hidden,
        });
      } else {
        setFormData({ type: 2, sort: 1, hidden: false });
      }
    }
  }, [open, record]);

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.name?.trim()) {
        toast({
          title: '提示',
          description: '请输入菜单名称',
          variant: 'destructive'
        });
        return;
      }

      if (!formData.type) {
        toast({
          title: '提示',
          description: '请选择菜单类型',
          variant: 'destructive'
        });
        return;
      }

      // 目录和菜单需要路由地址
      if (formData.type !== 3 && !formData.path?.trim()) {
        toast({
          title: '提示',
          description: '请输入路由地址',
          variant: 'destructive'
        });
        return;
      }

      // 菜单需要组件路径
      if (formData.type === 2 && !formData.component?.trim()) {
        toast({
          title: '提示',
          description: '请输入组件路径',
          variant: 'destructive'
        });
        return;
      }

      if (record) {
        await updateMenu(record.id, {
          ...formData as MenuRequest,
          version: record.version
        });
        toast({
          title: '更新成功',
          description: `菜单 "${formData.name}" 已更新`,
        });
      } else {
        await createMenu(formData as MenuRequest);
        toast({
          title: '创建成功',
          description: `菜单 "${formData.name}" 已创建`,
        });
      }

      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error('保存失败:', error);
      toast({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  // 扁平化菜单列表
  const flattenMenus = (menus: MenuResponse[], level: number = 0): Array<MenuResponse & { level: number }> => {
    const result: Array<MenuResponse & { level: number }> = [];
    menus.forEach(menu => {
      // 过滤掉自己，避免选择自己作为父菜单
      if (!record || menu.id !== record.id) {
        result.push({ ...menu, level });
        if (menu.children) {
          result.push(...flattenMenus(menu.children, level + 1));
        }
      }
    });
    return result;
  };

  const flatMenus = flattenMenus(menuTree);
  const isButton = formData.type === 3;

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{record ? '编辑菜单' : '新增菜单'}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="type">菜单类型 *</Label>
              <Select
                value={formData.type?.toString()}
                onValueChange={(value) => setFormData({ ...formData, type: Number(value) as MenuTypeEnum })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="请选择菜单类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">目录</SelectItem>
                  <SelectItem value="2">菜单</SelectItem>
                  <SelectItem value="3">按钮</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="name">菜单名称 *</Label>
              <Input
                id="name"
                value={formData.name || ''}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="请输入菜单名称"
              />
            </div>

            <div className="grid gap-2">
              <div className="flex items-center gap-2">
                <Label htmlFor="parentId">上级菜单</Label>
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <HelpCircle className="h-4 w-4 text-muted-foreground" />
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>不选择则为顶级菜单</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              </div>
              <Select
                value={formData.parentId?.toString() || 'none'}
                onValueChange={(value) => setFormData({ ...formData, parentId: value === 'none' ? undefined : Number(value) })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="不选择则为顶级菜单" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">顶级菜单</SelectItem>
                  {flatMenus.map(menu => (
                    <SelectItem key={menu.id} value={menu.id.toString()}>
                      {'　'.repeat(menu.level)}{menu.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {!isButton && (
              <>
                <div className="grid gap-2">
                  <Label htmlFor="icon">菜单图标</Label>
                  <div className="flex gap-2">
                    <Input
                      id="icon"
                      value={formData.icon || ''}
                      readOnly
                      placeholder="请选择图标"
                      onClick={() => setIconSelectVisible(true)}
                      className="flex-1 cursor-pointer"
                    />
                    {formData.icon && (
                      <div className="flex items-center justify-center w-10 h-10 border rounded-md">
                        {getIconComponent(formData.icon)}
                      </div>
                    )}
                  </div>
                </div>

                <div className="grid gap-2">
                  <Label htmlFor="path">路由地址 *</Label>
                  <Input
                    id="path"
                    value={formData.path || ''}
                    onChange={(e) => setFormData({ ...formData, path: e.target.value })}
                    placeholder="请输入路由地址"
                  />
                </div>

                {formData.type === 2 && (
                  <div className="grid gap-2">
                    <Label htmlFor="component">组件路径 *</Label>
                    <Input
                      id="component"
                      value={formData.component || ''}
                      onChange={(e) => setFormData({ ...formData, component: e.target.value })}
                      placeholder="请输入组件路径"
                    />
                  </div>
                )}
              </>
            )}

            <div className="grid gap-2">
              <Label htmlFor="sort">显示排序 *</Label>
              <Input
                id="sort"
                type="number"
                value={formData.sort || 1}
                onChange={(e) => setFormData({ ...formData, sort: Number(e.target.value) })}
                placeholder="请输入显示排序"
              />
            </div>

            <div className="flex items-center justify-between">
              <Label htmlFor="hidden">是否隐藏</Label>
              <Switch
                id="hidden"
                checked={formData.hidden}
                onCheckedChange={(checked) => setFormData({ ...formData, hidden: checked })}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              取消
            </Button>
            <Button onClick={handleSubmit}>确定</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 图标选择器 */}
      <IconSelect
        visible={iconSelectVisible}
        onCancel={() => setIconSelectVisible(false)}
        value={formData.icon}
        onChange={(value) => {
          setFormData({ ...formData, icon: value });
          setIconSelectVisible(false);
        }}
      />
    </>
  );
};

export default EditDialog;

