import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";
import { Target, TrendingUp, Clock, UserCircle2, Plus, Loader2 } from "lucide-react";
import { Goal } from "@/hooks/useGoals";

export interface ManagerGoal {
  id: string;
  title: string;
  description: string;
  targetValue: number;
  currentValue: number;
  unit: string;
  deadline: Date;
  assignedBy: string;
  priority: 'low' | 'medium' | 'high' | 'normal' | 'urgent';
}

interface ManagerGoalCardProps {
  goal?: ManagerGoal | Goal;
  loading?: boolean;
  onCreateGoal?: () => void;
}

const priorityConfig: Record<string, { label: string; color: string }> = {
  low: { label: "低", color: "bg-muted text-muted-foreground" },
  normal: { label: "普通", color: "bg-muted text-muted-foreground" },
  medium: { label: "中", color: "bg-amber-500/20 text-amber-600" },
  high: { label: "重要", color: "bg-amber-500/20 text-amber-600" },
  urgent: { label: "紧急", color: "bg-destructive/20 text-destructive" }
};

// 辅助函数：将数据库目标转换为组件格式
function normalizeGoal(goal: ManagerGoal | Goal): ManagerGoal {
  if ('target_value' in goal) {
    // 这是数据库格式的 Goal
    return {
      id: goal.id,
      title: goal.title,
      description: goal.description || '',
      targetValue: goal.target_value,
      currentValue: goal.current_value,
      unit: goal.unit,
      deadline: new Date(goal.deadline),
      assignedBy: goal.assigned_by || '经理AI · 小管',
      priority: goal.priority as ManagerGoal['priority']
    };
  }
  // 已经是 ManagerGoal 格式
  return goal;
}

export function ManagerGoalCard({ goal, loading, onCreateGoal }: ManagerGoalCardProps) {
  if (loading) {
    return (
      <Card className="bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
        <CardContent className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
              <Loader2 className="h-5 w-5 text-primary animate-spin" />
            </div>
            <div>
              <p className="text-sm text-muted-foreground">加载中...</p>
              <p className="font-medium">正在获取目标数据</p>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!goal) {
    return (
      <Card className="bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
        <CardContent className="p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
                <Target className="h-5 w-5 text-primary" />
              </div>
              <div>
                <p className="text-sm text-muted-foreground">来自经理的目标</p>
                <p className="font-medium">暂无分配的目标</p>
              </div>
            </div>
            {onCreateGoal && (
              <Button variant="outline" size="sm" onClick={onCreateGoal}>
                <Plus className="h-4 w-4 mr-1" />
                创建目标
              </Button>
            )}
          </div>
          <p className="text-sm text-muted-foreground mt-3">
            提示：您可以通过AI助手创建目标，例如：「设置本月营销GMV目标35万元，截止日期月底」
          </p>
        </CardContent>
      </Card>
    );
  }

  const normalizedGoal = normalizeGoal(goal);
  const progress = Math.min((normalizedGoal.currentValue / normalizedGoal.targetValue) * 100, 100);
  const daysLeft = Math.ceil((normalizedGoal.deadline.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
  const priority = priorityConfig[normalizedGoal.priority] || priorityConfig.medium;

  return (
    <Card className="bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
      <CardContent className="p-4">
        <div className="flex items-start justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
              <Target className="h-5 w-5 text-primary" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <p className="text-sm text-muted-foreground">来自经理的目标</p>
                <Badge className={`text-xs ${priority.color}`}>
                  {priority.label}
                </Badge>
              </div>
              <p className="font-semibold">{normalizedGoal.title}</p>
            </div>
          </div>
          
          <div className="text-right">
            <div className="flex items-center gap-1 text-xs text-muted-foreground">
              <Clock className="h-3 w-3" />
              {daysLeft > 0 ? `剩余 ${daysLeft} 天` : '已过期'}
            </div>
          </div>
        </div>
        
        {normalizedGoal.description && (
          <p className="text-sm text-muted-foreground mb-3">{normalizedGoal.description}</p>
        )}
        
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">完成进度</span>
            <span className="font-medium">
              {normalizedGoal.currentValue.toLocaleString()} / {normalizedGoal.targetValue.toLocaleString()} {normalizedGoal.unit}
            </span>
          </div>
          <Progress value={progress} className="h-2" />
          <div className="flex items-center justify-between text-xs text-muted-foreground">
            <div className="flex items-center gap-1">
              <UserCircle2 className="h-3 w-3" />
              分配者: {normalizedGoal.assignedBy}
            </div>
            <div className="flex items-center gap-1">
              <TrendingUp className="h-3 w-3" />
              {progress.toFixed(1)}% 完成
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
