'use client';

import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card } from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Info } from 'lucide-react';
import { getRoles, getUsers, type Role, type User } from '@/services/api/organization';

export type FallbackType = 'NONE' | 'UP_CHAIN' | 'FIXED_USER' | 'SYSTEM_ROLE';

export interface FallbackConfig {
  fallbackType: FallbackType;
  fallbackConfig?: {
    maxLevel?: number;
    userId?: string;
    roleCode?: string;
  };
}

interface FallbackStrategyConfigProps {
  value?: FallbackConfig;
  onChange: (config: FallbackConfig) => void;
  className?: string;
}

const FALLBACK_TYPES = [
  {
    value: 'NONE',
    label: '不兜底',
    description: '解析结果为空时返回空，流程报错',
  },
  {
    value: 'UP_CHAIN',
    label: '向上追溯',
    description: '找不到审批人时沿汇报链向上查找',
  },
  {
    value: 'FIXED_USER',
    label: '固定用户',
    description: '指定特定用户作为兜底审批人',
  },
  {
    value: 'SYSTEM_ROLE',
    label: '系统角色',
    description: '指定系统角色的所有用户作为兜底审批人',
  },
];

export function FallbackStrategyConfig({ value, onChange, className }: FallbackStrategyConfigProps) {
  const [fallbackType, setFallbackType] = useState<FallbackType>(value?.fallbackType || 'NONE');
  const [maxLevel, setMaxLevel] = useState<number>(value?.fallbackConfig?.maxLevel || 5);
  const [userId, setUserId] = useState<string>(value?.fallbackConfig?.userId || '');
  const [roleCode, setRoleCode] = useState<string>(value?.fallbackConfig?.roleCode || '');

  const [roles, setRoles] = useState<Role[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);

  // Load roles and users
  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      setLoading(true);
      const [rolesData, usersData] = await Promise.all([
        getRoles(),
        getUsers({ pageSize: 1000 }),
      ]);
      setRoles(rolesData);
      setUsers(Array.isArray(usersData) ? usersData : (usersData.items || []));
    } catch (error) {
      console.error('Failed to load fallback config data:', error);
    } finally {
      setLoading(false);
    }
  };

  // Update parent when config changes
  useEffect(() => {
    const config: FallbackConfig = {
      fallbackType,
      fallbackConfig: {},
    };

    if (fallbackType === 'UP_CHAIN') {
      config.fallbackConfig = { maxLevel };
    } else if (fallbackType === 'FIXED_USER' && userId) {
      config.fallbackConfig = { userId };
    } else if (fallbackType === 'SYSTEM_ROLE' && roleCode) {
      config.fallbackConfig = { roleCode };
    }

    onChange(config);
  }, [fallbackType, maxLevel, userId, roleCode, onChange]);

  return (
    <Card className={`p-6 ${className || ''}`}>
      <div className="space-y-4">
        <div>
          <Label className="text-base font-semibold">兜底策略 (Fallback Strategy)</Label>
          <p className="text-sm text-gray-500 mt-1">
            当规则解析结果为空时的处理方式
          </p>
        </div>

        <RadioGroup value={fallbackType} onValueChange={(v) => setFallbackType(v as FallbackType)}>
          <div className="space-y-3">
            {FALLBACK_TYPES.map((type) => (
              <div key={type.value} className="flex items-start space-x-3 p-3 border rounded-lg hover:bg-gray-50">
                <RadioGroupItem value={type.value} id={`fallback-${type.value}`} className="mt-1" />
                <div className="flex-1">
                  <Label htmlFor={`fallback-${type.value}`} className="font-medium cursor-pointer">
                    {type.label}
                  </Label>
                  <p className="text-sm text-gray-500">{type.description}</p>

                  {/* UP_CHAIN specific config */}
                  {fallbackType === 'UP_CHAIN' && type.value === 'UP_CHAIN' && (
                    <div className="mt-3">
                      <Label htmlFor="maxLevel" className="text-sm">最大追溯层级</Label>
                      <Input
                        id="maxLevel"
                        type="number"
                        min="1"
                        max="20"
                        value={maxLevel}
                        onChange={(e) => setMaxLevel(parseInt(e.target.value) || 5)}
                        className="mt-1 w-32"
                        placeholder="默认 5"
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        设置为 0 表示无限追溯（建议设置上限避免死循环）
                      </p>
                    </div>
                  )}

                  {/* FIXED_USER specific config */}
                  {fallbackType === 'FIXED_USER' && type.value === 'FIXED_USER' && (
                    <div className="mt-3">
                      <Label htmlFor="userId" className="text-sm">兜底用户</Label>
                      <Select value={userId} onValueChange={setUserId} disabled={loading}>
                        <SelectTrigger className="mt-1">
                          <SelectValue placeholder="选择兜底用户" />
                        </SelectTrigger>
                        <SelectContent>
                          {users.map((user) => (
                            <SelectItem key={user.id} value={user.id}>
                              {user.displayName} ({user.email})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}

                  {/* SYSTEM_ROLE specific config */}
                  {fallbackType === 'SYSTEM_ROLE' && type.value === 'SYSTEM_ROLE' && (
                    <div className="mt-3">
                      <Label htmlFor="roleCode" className="text-sm">兜底角色</Label>
                      <Select value={roleCode} onValueChange={setRoleCode} disabled={loading}>
                        <SelectTrigger className="mt-1">
                          <SelectValue placeholder="选择兜底角色" />
                        </SelectTrigger>
                        <SelectContent>
                          {roles.map((role) => (
                            <SelectItem key={role.id} value={role.code}>
                              {role.name} ({role.code})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </RadioGroup>

        {/* Info Alert */}
        <Alert>
          <Info className="h-4 w-4" />
          <AlertDescription className="text-sm">
            <strong>提示：</strong>
            {fallbackType === 'NONE' && ' 不配置兜底策略时，如果规则解析为空，流程将无法继续执行。'}
            {fallbackType === 'UP_CHAIN' && ' 向上追溯策略会沿着申请人的汇报链向上查找，直到找到有效审批人或达到最大层级。'}
            {fallbackType === 'FIXED_USER' && ' 固定用户策略会在规则解析失败时，使用指定的用户作为审批人。'}
            {fallbackType === 'SYSTEM_ROLE' && ' 系统角色策略会在规则解析失败时，使用指定角色的所有用户作为审批人。'}
          </AlertDescription>
        </Alert>
      </div>
    </Card>
  );
}

