/**
 * filekorolheader: 权限管理对话框组件 - 模型访问权限设置
 * 功能：访问级别、API限流配置、IP白名单管理
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */

'use client';

import { useState } from 'react';
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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Plus, X, Shield, Clock, Globe } from 'lucide-react';
import { toast } from 'sonner';

interface PermissionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  model: any;
}

export function PermissionDialog({ open, onOpenChange, model }: PermissionDialogProps) {
  const [accessLevel, setAccessLevel] = useState(model?.visibility || 'private');
  const [ipWhitelist, setIpWhitelist] = useState<string[]>(['192.168.1.100', '10.0.0.50']);
  const [newIp, setNewIp] = useState('');
  const [apiRateLimit, setApiRateLimit] = useState({
    enabled: true,
    requestsPerMinute: 100,
    requestsPerHour: 1000,
    requestsPerDay: 10000
  });
  const [authRequired, setAuthRequired] = useState(true);
  const [apiKeyRequired, setApiKeyRequired] = useState(true);

  const addIpToWhitelist = () => {
    if (newIp && !ipWhitelist.includes(newIp)) {
      setIpWhitelist([...ipWhitelist, newIp]);
      setNewIp('');
    }
  };

  const removeIpFromWhitelist = (ip: string) => {
    setIpWhitelist(ipWhitelist.filter(ipAddr => ipAddr !== ip));
  };

  const savePermissions = () => {
    toast.success('权限设置已保存');
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>权限管理</DialogTitle>
          <DialogDescription>
            设置模型 <strong>{model?.name}</strong> 的访问权限和安全配置
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 访问级别 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Globe className="w-5 h-5 text-blue-600" />
              <Label className="text-base font-medium">访问级别</Label>
            </div>
            <div className="space-y-3">
              <div className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50">
                <div className="flex items-center space-x-3">
                  <input
                    type="radio"
                    name="access"
                    checked={accessLevel === 'public'}
                    onChange={() => setAccessLevel('public')}
                    className="w-4 h-4"
                  />
                  <div>
                    <div className="font-medium">公开访问</div>
                    <div className="text-sm text-muted-foreground">
                      所有人都可以访问此模型API
                    </div>
                  </div>
                </div>
                <Badge className="bg-green-100 text-green-800">公开</Badge>
              </div>

              <div className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50">
                <div className="flex items-center space-x-3">
                  <input
                    type="radio"
                    name="access"
                    checked={accessLevel === 'team'}
                    onChange={() => setAccessLevel('team')}
                    className="w-4 h-4"
                  />
                  <div>
                    <div className="font-medium">团队访问</div>
                    <div className="text-sm text-muted-foreground">
                      仅限团队成员可以访问此模型
                    </div>
                  </div>
                </div>
                <Badge className="bg-blue-100 text-blue-800">团队</Badge>
              </div>

              <div className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50">
                <div className="flex items-center space-x-3">
                  <input
                    type="radio"
                    name="access"
                    checked={accessLevel === 'private'}
                    onChange={() => setAccessLevel('private')}
                    className="w-4 h-4"
                  />
                  <div>
                    <div className="font-medium">私有访问</div>
                    <div className="text-sm text-muted-foreground">
                      仅您可以访问此模型
                    </div>
                  </div>
                </div>
                <Badge className="bg-red-100 text-red-800">私有</Badge>
              </div>
            </div>
          </div>

          {/* API限流配置 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Clock className="w-5 h-5 text-orange-600" />
              <Label className="text-base font-medium">API限流配置</Label>
            </div>
            <div className="flex items-center justify-between p-4 border rounded-lg">
              <div>
                <div className="font-medium">启用API限流</div>
                <div className="text-sm text-muted-foreground">
                  限制API调用频率，防止滥用
                </div>
              </div>
              <Switch
                checked={apiRateLimit.enabled}
                onCheckedChange={(checked) => setApiRateLimit(prev => ({ ...prev, enabled: checked }))}
              />
            </div>

            {apiRateLimit.enabled && (
              <div className="grid grid-cols-3 gap-4 p-4 border rounded-lg bg-muted/30">
                <div className="space-y-2">
                  <Label>每分钟限制</Label>
                  <Input
                    type="number"
                    value={apiRateLimit.requestsPerMinute}
                    onChange={(e) => setApiRateLimit(prev => ({
                      ...prev,
                      requestsPerMinute: parseInt(e.target.value) || 0
                    }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>每小时限制</Label>
                  <Input
                    type="number"
                    value={apiRateLimit.requestsPerHour}
                    onChange={(e) => setApiRateLimit(prev => ({
                      ...prev,
                      requestsPerHour: parseInt(e.target.value) || 0
                    }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label>每天限制</Label>
                  <Input
                    type="number"
                    value={apiRateLimit.requestsPerDay}
                    onChange={(e) => setApiRateLimit(prev => ({
                      ...prev,
                      requestsPerDay: parseInt(e.target.value) || 0
                    }))}
                  />
                </div>
              </div>
            )}
          </div>

          {/* IP白名单 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Shield className="w-5 h-5 text-green-600" />
              <Label className="text-base font-medium">IP白名单</Label>
            </div>
            <div className="space-y-3">
              <div className="flex space-x-2">
                <Input
                  placeholder="输入IP地址添加到白名单"
                  value={newIp}
                  onChange={(e) => setNewIp(e.target.value)}
                  className="flex-1"
                />
                <Button onClick={addIpToWhitelist} size="sm">
                  <Plus className="w-4 h-4" />
                </Button>
              </div>
              <div className="space-y-2">
                {ipWhitelist.map((ip, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-muted rounded">
                    <div className="flex items-center space-x-2">
                      <Globe className="w-4 h-4 text-muted-foreground" />
                      <code className="text-sm font-mono">{ip}</code>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeIpFromWhitelist(ip)}
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
                {ipWhitelist.length === 0 && (
                  <div className="text-center text-muted-foreground py-4">
                    暂无IP白名单配置
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* 认证设置 */}
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Shield className="w-5 h-5 text-purple-600" />
              <Label className="text-base font-medium">认证设置</Label>
            </div>
            <div className="space-y-3">
              <div className="flex items-center justify-between p-4 border rounded-lg">
                <div>
                  <div className="font-medium">需要身份验证</div>
                  <div className="text-sm text-muted-foreground">
                    访问API前需要用户登录验证
                  </div>
                </div>
                <Switch
                  checked={authRequired}
                  onCheckedChange={setAuthRequired}
                />
              </div>

              <div className="flex items-center justify-between p-4 border rounded-lg">
                <div>
                  <div className="font-medium">需要API密钥</div>
                  <div className="text-sm text-muted-foreground">
                    API调用需要提供有效的API密钥
                  </div>
                </div>
                <Switch
                  checked={apiKeyRequired}
                  onCheckedChange={setApiKeyRequired}
                />
              </div>
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={savePermissions}>
            保存设置
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}