'use client';

import React from 'react';
import { Dialog, DialogContent, DialogDescription, 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 { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Card } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChevronRight, Loader2 } from 'lucide-react';
import { Role, RoleFormData, allSystemMenus } from '../types';

interface RoleFormDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  editingRole: Role | null;
  formData: RoleFormData;
  onFormDataChange: (data: RoleFormData) => void;
  onSave: () => void;
  editFormLoading?: boolean;
}

export function RoleFormDialog({
  open,
  onOpenChange,
  editingRole,
  formData,
  onFormDataChange,
  onSave,
  editFormLoading = false
}: RoleFormDialogProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>{editingRole ? '编辑角色' : '添加角色'}</DialogTitle>
          <DialogDescription className="sr-only">
            {editingRole ? '编辑角色信息' : '添加新角色'}
          </DialogDescription>
        </DialogHeader>

        {/* Loading state for edit form */}
        {editFormLoading && editingRole ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-6 w-6 animate-spin mr-2" />
            <span>正在加载角色数据...</span>
          </div>
        ) : (
          <ScrollArea className="max-h-[calc(90vh-180px)]">
            <div className="space-y-6 pr-4">
            {/* 基本信息 */}
            <div className="space-y-4">
              <h4 className="text-green-800">基本信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">角色名称 *</Label>
                  <Input
                    id="name"
                    value={formData.name || ''}
                    onChange={(e) => onFormDataChange({ ...formData, name: e.target.value })}
                    placeholder="如：数据分析员"
                  />
                </div>
                <div>
                  <Label htmlFor="code">角色代码 *</Label>
                  <Input
                    id="code"
                    value={formData.code || ''}
                    onChange={(e) => onFormDataChange({ ...formData, code: e.target.value })}
                    placeholder="如：data_analyst"
                  />
                </div>
              </div>
              <div>
                <Label htmlFor="description">角色描述</Label>
                <Textarea
                  id="description"
                  value={formData.description || ''}
                  onChange={(e) => onFormDataChange({ ...formData, description: e.target.value })}
                  rows={3}
                  placeholder="描述角色的职责和权限范围..."
                />
              </div>
              <div>
                <Label htmlFor="defaultHomePage">默认首页</Label>
                <Input
                  id="defaultHomePage"
                  value={formData.defaultHomePage || ''}
                  onChange={(e) => onFormDataChange({ ...formData, defaultHomePage: e.target.value })}
                  placeholder="/machinery/monitoring/location"
                />
              </div>
            </div>

            {/* 菜单与操作权限 */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-green-800">菜单与操作权限</h4>
                <p className="text-xs text-muted-foreground">选择菜单后可配置该菜单下的操作权限</p>
              </div>
              <Card className="p-4 bg-gray-50 bg-input-background">
                <div className="space-y-6">
                  {allSystemMenus.map((system) => (
                    <div key={system.id} className="space-y-3">
                      {/* 系统级别 */}
                      <div className="flex items-center gap-2 pb-2 border-b border-green-200">
                        <Checkbox
                          id={`system-${system.id}`}
                          checked={
                            formData.menuIds?.includes('*') ||
                            (system.menus.every(menu =>
                              formData.menuIds?.includes(menu.id)
                            ) && system.menus.length > 0)
                          }
                          onCheckedChange={(checked) => {
                            if (checked) {
                              // 选中所有一级菜单
                              const allMenuIds = system.menus.map(m => m.id);
                              onFormDataChange({
                                ...formData,
                                menuIds: Array.from(new Set([...(formData.menuIds || []), ...allMenuIds])),
                              });
                            } else {
                              // 取消选中所有一级菜单
                              const menuIdsToRemove = system.menus.map(m => m.id);
                              onFormDataChange({
                                ...formData,
                                menuIds: (formData.menuIds || []).filter(id => !menuIdsToRemove.includes(id)),
                              });
                            }
                          }}
                          disabled={formData.menuIds?.includes('*')}
                        />
                        <Label htmlFor={`system-${system.id}`} className="cursor-pointer text-green-700">
                          {system.label}
                        </Label>
                      </div>

                      {/* 一级菜单 */}
                      <div className="ml-6 space-y-4">
                        {system.menus.map((menu) => (
                          <div key={menu.id} className="space-y-2">
                            <div className="flex items-center gap-2">
                              <Checkbox
                                id={`menu-${menu.id}`}
                                checked={formData.menuIds?.includes(menu.id) || formData.menuIds?.includes('*')}
                                onCheckedChange={(checked) => {
                                  if (checked) {
                                    onFormDataChange({
                                      ...formData,
                                      menuIds: [...(formData.menuIds || []), menu.id],
                                    });
                                  } else {
                                    // 取消菜单时，同时取消该菜单下的所有权限
                                    const childrenIds = menu.children?.map(c => c.id) || [];
                                    const permissionsToRemove = menu.children?.flatMap(c =>
                                      c.operations.map(op => op.id)
                                    ) || [];

                                    onFormDataChange({
                                      ...formData,
                                      menuIds: (formData.menuIds || []).filter(id =>
                                        id !== menu.id && !childrenIds.includes(id)
                                      ),
                                      permissionIds: (formData.permissionIds || []).filter(id =>
                                        !permissionsToRemove.includes(id)
                                      ),
                                    });
                                  }
                                }}
                                disabled={formData.menuIds?.includes('*')}
                              />
                              <Label htmlFor={`menu-${menu.id}`} className="cursor-pointer">
                                {menu.label}
                              </Label>
                            </div>

                            {/* 二级菜单及其操作权限 */}
                            {menu.children && (formData.menuIds?.includes(menu.id) || formData.menuIds?.includes('*')) && (
                              <div className="ml-6 space-y-3 pl-4 border-l-2 border-green-100">
                                {menu.children.map((child) => (
                                  <div key={child.id} className="space-y-2">
                                    <div className="flex items-center gap-2">
                                      <ChevronRight className="w-3 h-3 text-green-600" />
                                      <span className="text-sm text-muted-foreground">{child.label}</span>
                                    </div>
                                    <div className="ml-5 flex flex-wrap gap-3">
                                      {child.operations.map((operation) => (
                                        <div key={operation.id} className="flex items-center gap-1.5">
                                          <Checkbox
                                            id={`permission-${operation.id}`}
                                            checked={
                                              formData.permissionIds?.includes(operation.id) ||
                                              formData.permissionIds?.includes('*')
                                            }
                                            onCheckedChange={(checked) => {
                                              if (checked) {
                                                onFormDataChange({
                                                  ...formData,
                                                  permissionIds: [...(formData.permissionIds || []), operation.id],
                                                });
                                              } else {
                                                onFormDataChange({
                                                  ...formData,
                                                  permissionIds: (formData.permissionIds || []).filter(id => id !== operation.id),
                                                });
                                              }
                                            }}
                                            disabled={formData.permissionIds?.includes('*')}
                                          />
                                          <Label
                                            htmlFor={`permission-${operation.id}`}
                                            className="text-xs cursor-pointer text-foreground"
                                          >
                                            {operation.label}
                                          </Label>
                                        </div>
                                      ))}
                                    </div>
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          </div>
          </ScrollArea>
        )}
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={onSave}>保存</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}