import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
import { Loader2, Save, MessageSquare, Shield, Bell, Target } from 'lucide-react';
import { AI_AGENTS, AIAgent } from '@/types/agents';

interface AgentSettings {
  id: string;
  agent_type: string;
  response_style: string;
  tone: string;
  auto_execute_enabled: boolean;
  max_auto_amount: number;
  requires_approval_types: string[] | null;
  notify_on_insights: boolean;
  notify_on_approvals: boolean;
  notify_on_errors: boolean;
  monthly_goals: Record<string, any> | null;
  is_active: boolean;
}

interface AgentSettingsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  agentType?: string; // If provided, opens directly to this agent
}

const RESPONSE_STYLES = [
  { value: 'concise', label: '简洁', description: '简短直接的回复' },
  { value: 'balanced', label: '均衡', description: '适中的详细程度' },
  { value: 'detailed', label: '详细', description: '完整详尽的回复' },
];

const TONES = [
  { value: 'professional', label: '专业', description: '正式商务风格' },
  { value: 'friendly', label: '友好', description: '亲切温和风格' },
  { value: 'formal', label: '正式', description: '严谨规范风格' },
];

const APPROVAL_TYPES: Record<string, { value: string; label: string; description?: string }[]> = {
  manager: [
    { value: 'create_product', label: '创建商品', description: '创建新商品需要审批' },
    { value: 'update_price', label: '修改价格', description: '价格变动需要审批' },
    { value: 'create_campaign', label: '创建活动', description: '创建营销活动需要审批' },
    { value: 'large_discount', label: '大额折扣', description: '超过阈值的折扣需要审批' },
  ],
  marketing: [
    { value: 'create_campaign', label: '创建活动', description: '创建营销活动需要审批' },
    { value: 'large_discount', label: '大额折扣', description: '超过阈值的折扣需要审批' },
    { value: 'coupon_create', label: '创建优惠券', description: '创建优惠券需要审批' },
  ],
  product: [
    { value: 'create_product', label: '创建商品', description: '创建新商品需要审批' },
    { value: 'update_price', label: '修改价格', description: '价格变动需要审批' },
    { value: 'stock_adjustment', label: '库存调整', description: '库存调整需要审批' },
  ],
  service: [
    { value: 'approve_refund', label: '退款审批', description: '退款申请需要审批' },
    { value: 'approve_return', label: '退货审批', description: '退货申请需要审批' },
    { value: 'approve_exchange', label: '换货审批', description: '换货申请需要审批' },
    { value: 'compensation', label: '补偿处理', description: '客户补偿需要审批' },
  ],
  finance: [
    { value: 'approve_refund', label: '退款审批', description: '退款申请需要审批' },
    { value: 'large_payment', label: '大额支付', description: '超过阈值的支付需要审批' },
    { value: 'price_adjustment', label: '价格调整', description: '价格调整需要审批' },
  ],
};

// 售后类型的自动审批条件
const AFTERSALES_AUTO_CONDITIONS = [
  { value: 'amount_limit', label: '金额限制', description: '低于设定金额的申请可自动通过' },
  { value: 'first_request', label: '首次申请', description: '用户首次售后申请可自动通过' },
  { value: 'vip_user', label: 'VIP用户', description: 'VIP用户的申请可自动通过' },
  { value: 'within_7days', label: '7天内订单', description: '7天内订单可自动通过' },
];

export const AgentSettingsDialog: React.FC<AgentSettingsDialogProps> = ({
  open,
  onOpenChange,
  agentType,
}) => {
  const [settings, setSettings] = useState<AgentSettings[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeAgent, setActiveAgent] = useState(agentType || 'manager');

  useEffect(() => {
    if (open) {
      loadSettings();
      if (agentType) {
        setActiveAgent(agentType);
      }
    }
  }, [open, agentType]);

  const loadSettings = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('agent_settings')
        .select('*')
        .order('agent_type');

      if (error) throw error;
      setSettings((data || []) as AgentSettings[]);
    } catch (error) {
      console.error('Error loading agent settings:', error);
      toast.error('加载设置失败');
    } finally {
      setLoading(false);
    }
  };

  const updateSetting = (agentType: string, field: keyof AgentSettings, value: any) => {
    setSettings(prev => prev.map(s => 
      s.agent_type === agentType ? { ...s, [field]: value } : s
    ));
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      const currentSetting = settings.find(s => s.agent_type === activeAgent);
      if (!currentSetting) return;

      const { error } = await supabase
        .from('agent_settings')
        .update({
          response_style: currentSetting.response_style,
          tone: currentSetting.tone,
          auto_execute_enabled: currentSetting.auto_execute_enabled,
          max_auto_amount: currentSetting.max_auto_amount,
          requires_approval_types: currentSetting.requires_approval_types,
          notify_on_insights: currentSetting.notify_on_insights,
          notify_on_approvals: currentSetting.notify_on_approvals,
          notify_on_errors: currentSetting.notify_on_errors,
          monthly_goals: currentSetting.monthly_goals,
          is_active: currentSetting.is_active,
        })
        .eq('agent_type', activeAgent);

      if (error) throw error;
      toast.success('设置已保存');
    } catch (error) {
      console.error('Error saving settings:', error);
      toast.error('保存失败');
    } finally {
      setSaving(false);
    }
  };

  const getAgentInfo = (type: string): AIAgent => {
    return AI_AGENTS[type as keyof typeof AI_AGENTS] || AI_AGENTS.manager;
  };

  const getCurrentSettings = (): AgentSettings | undefined => {
    return settings.find(s => s.agent_type === activeAgent);
  };

  const currentSettings = getCurrentSettings();
  const agentInfo = getAgentInfo(activeAgent);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[85vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <span>AI团队管理</span>
            <Badge variant="outline">5位成员</Badge>
          </DialogTitle>
          <DialogDescription>
            配置各AI助理的行为偏好、决策权限和目标设定
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <div className="flex-1 overflow-hidden flex gap-4">
            {/* Agent List - Left Side */}
            <div className="w-48 flex-shrink-0 space-y-1 overflow-y-auto">
              {Object.entries(AI_AGENTS).map(([key, agent]) => (
                <button
                  key={key}
                  onClick={() => setActiveAgent(key)}
                  className={`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${
                    activeAgent === key 
                      ? 'bg-primary text-primary-foreground' 
                      : 'hover:bg-muted'
                  }`}
                >
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={agent.avatar} alt={agent.name} />
                    <AvatarFallback>{agent.emoji}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium truncate">{agent.name}</p>
                    <p className={`text-xs truncate ${activeAgent === key ? 'opacity-80' : 'text-muted-foreground'}`}>
                      {agent.role}
                    </p>
                  </div>
                </button>
              ))}
            </div>

            {/* Settings Panel - Right Side */}
            <div className="flex-1 overflow-y-auto">
              {currentSettings && (
                <div className="space-y-6">
                  {/* Agent Header */}
                  <div className="flex items-center gap-4 pb-4 border-b">
                    <Avatar className="h-12 w-12">
                      <AvatarImage src={agentInfo.avatar} alt={agentInfo.name} />
                      <AvatarFallback className="text-lg">{agentInfo.emoji}</AvatarFallback>
                    </Avatar>
                    <div className="flex-1">
                      <h3 className="text-lg font-semibold">{agentInfo.name}</h3>
                      <p className="text-sm text-muted-foreground">{agentInfo.description}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      <Label htmlFor="agent-active" className="text-sm">启用</Label>
                      <Switch
                        id="agent-active"
                        checked={currentSettings.is_active}
                        onCheckedChange={(v) => updateSetting(activeAgent, 'is_active', v)}
                      />
                    </div>
                  </div>

                  <Tabs defaultValue="style" className="w-full">
                    <TabsList className="grid w-full grid-cols-4">
                      <TabsTrigger value="style" className="text-xs">
                        <MessageSquare className="h-3 w-3 mr-1" />
                        响应风格
                      </TabsTrigger>
                      <TabsTrigger value="authority" className="text-xs">
                        <Shield className="h-3 w-3 mr-1" />
                        决策权限
                      </TabsTrigger>
                      <TabsTrigger value="notification" className="text-xs">
                        <Bell className="h-3 w-3 mr-1" />
                        通知设置
                      </TabsTrigger>
                      <TabsTrigger value="goals" className="text-xs">
                        <Target className="h-3 w-3 mr-1" />
                        目标设定
                      </TabsTrigger>
                    </TabsList>

                    {/* Response Style Tab */}
                    <TabsContent value="style" className="space-y-4 mt-4">
                      <div className="space-y-3">
                        <Label>回复详细程度</Label>
                        <Select
                          value={currentSettings.response_style}
                          onValueChange={(v) => updateSetting(activeAgent, 'response_style', v)}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {RESPONSE_STYLES.map(style => (
                              <SelectItem key={style.value} value={style.value}>
                                <div>
                                  <span className="font-medium">{style.label}</span>
                                  <span className="text-muted-foreground ml-2 text-xs">{style.description}</span>
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-3">
                        <Label>语气风格</Label>
                        <Select
                          value={currentSettings.tone}
                          onValueChange={(v) => updateSetting(activeAgent, 'tone', v)}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {TONES.map(tone => (
                              <SelectItem key={tone.value} value={tone.value}>
                                <div>
                                  <span className="font-medium">{tone.label}</span>
                                  <span className="text-muted-foreground ml-2 text-xs">{tone.description}</span>
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </TabsContent>

                    {/* Authority Tab */}
                    <TabsContent value="authority" className="space-y-4 mt-4">
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <Label>自动执行</Label>
                          <p className="text-xs text-muted-foreground">允许AI自动执行低风险操作</p>
                        </div>
                        <Switch
                          checked={currentSettings.auto_execute_enabled}
                          onCheckedChange={(v) => updateSetting(activeAgent, 'auto_execute_enabled', v)}
                        />
                      </div>

                      {currentSettings.auto_execute_enabled && (
                        <>
                          <div className="space-y-3">
                            <Label>自动执行金额上限 (元)</Label>
                            <Input
                              type="number"
                              value={currentSettings.max_auto_amount}
                              onChange={(e) => updateSetting(activeAgent, 'max_auto_amount', Number(e.target.value))}
                              placeholder="0 表示不限制"
                            />
                            <p className="text-xs text-muted-foreground">
                              低于此金额的操作可由AI自动执行，设为0表示不限制金额
                            </p>
                          </div>

                          {/* 售后Agent专属：自动审批条件 */}
                          {activeAgent === 'service' && (
                            <div className="space-y-3 p-4 bg-muted/50 rounded-lg">
                              <Label className="text-sm font-medium">自动审批条件</Label>
                              <p className="text-xs text-muted-foreground mb-2">
                                满足以下条件的售后申请可由AI自动通过
                              </p>
                              <div className="grid grid-cols-2 gap-2">
                                {AFTERSALES_AUTO_CONDITIONS.map(condition => {
                                  const monthlyGoals = currentSettings.monthly_goals || {};
                                  const autoConditions = (monthlyGoals.auto_conditions || []) as string[];
                                  return (
                                    <div key={condition.value} className="flex items-start gap-2 p-2 border rounded bg-background">
                                      <Switch
                                        id={`condition-${condition.value}`}
                                        checked={autoConditions.includes(condition.value)}
                                        onCheckedChange={(checked) => {
                                          const newConditions = checked
                                            ? [...autoConditions, condition.value]
                                            : autoConditions.filter(c => c !== condition.value);
                                          updateSetting(activeAgent, 'monthly_goals', {
                                            ...monthlyGoals,
                                            auto_conditions: newConditions,
                                          });
                                        }}
                                      />
                                      <div>
                                        <Label htmlFor={`condition-${condition.value}`} className="text-sm cursor-pointer">
                                          {condition.label}
                                        </Label>
                                        <p className="text-xs text-muted-foreground">{condition.description}</p>
                                      </div>
                                    </div>
                                  );
                                })}
                              </div>
                            </div>
                          )}
                        </>
                      )}

                      <div className="space-y-3">
                        <Label>需要人工审批的操作</Label>
                        <p className="text-xs text-muted-foreground mb-2">
                          开启后，对应操作必须经人工确认才能执行
                        </p>
                        <div className="grid grid-cols-2 gap-2">
                          {(APPROVAL_TYPES[activeAgent] || APPROVAL_TYPES.manager).map(type => (
                            <div key={type.value} className="flex items-start gap-2 p-2 border rounded">
                              <Switch
                                id={`approval-${type.value}`}
                                checked={(currentSettings.requires_approval_types || []).includes(type.value)}
                                onCheckedChange={(checked) => {
                                  const currentTypes = currentSettings.requires_approval_types || [];
                                  const types = checked
                                    ? [...currentTypes, type.value]
                                    : currentTypes.filter(t => t !== type.value);
                                  updateSetting(activeAgent, 'requires_approval_types', types);
                                }}
                              />
                              <div>
                                <Label htmlFor={`approval-${type.value}`} className="text-sm cursor-pointer">
                                  {type.label}
                                </Label>
                                {type.description && (
                                  <p className="text-xs text-muted-foreground">{type.description}</p>
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </TabsContent>

                    {/* Notification Tab */}
                    <TabsContent value="notification" className="space-y-4 mt-4">
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <Label>洞察通知</Label>
                          <p className="text-xs text-muted-foreground">收到AI发现的业务洞察时通知</p>
                        </div>
                        <Switch
                          checked={currentSettings.notify_on_insights}
                          onCheckedChange={(v) => updateSetting(activeAgent, 'notify_on_insights', v)}
                        />
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <Label>审批通知</Label>
                          <p className="text-xs text-muted-foreground">有待审批项目时通知</p>
                        </div>
                        <Switch
                          checked={currentSettings.notify_on_approvals}
                          onCheckedChange={(v) => updateSetting(activeAgent, 'notify_on_approvals', v)}
                        />
                      </div>

                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <Label>错误通知</Label>
                          <p className="text-xs text-muted-foreground">AI执行出错时通知</p>
                        </div>
                        <Switch
                          checked={currentSettings.notify_on_errors}
                          onCheckedChange={(v) => updateSetting(activeAgent, 'notify_on_errors', v)}
                        />
                      </div>
                    </TabsContent>

                    {/* Goals Tab */}
                    <TabsContent value="goals" className="space-y-4 mt-4">
                      <div className="p-4 bg-muted/50 rounded-lg">
                        <p className="text-sm text-muted-foreground">
                          目标设定功能即将推出，将支持为每个AI助理设定月度KPI和优化方向。
                        </p>
                      </div>
                      <div className="p-4 border rounded-lg">
                        <Label className="text-sm font-medium">当前目标配置</Label>
                        <pre className="mt-2 text-xs bg-muted p-2 rounded overflow-auto">
                          {JSON.stringify(currentSettings.monthly_goals || {}, null, 2)}
                        </pre>
                      </div>
                    </TabsContent>
                  </Tabs>

                  {/* Save Button */}
                  <div className="flex justify-end pt-4 border-t">
                    <Button onClick={saveSettings} disabled={saving}>
                      {saving ? (
                        <Loader2 className="h-4 w-4 animate-spin mr-2" />
                      ) : (
                        <Save className="h-4 w-4 mr-2" />
                      )}
                      保存设置
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
};
