"use client";

import { Task } from "@/features/tasks/types";
import { Member } from "@/features/members/types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { formatDistanceToNow } from "date-fns";
import { 
  CheckCircle, 
  Clock, 
  AlertCircle, 
  Calendar,
  TrendingUp,
  TrendingDown,
  Users,
  BarChart3,
  Plus,
  Edit3,
  ArrowRight,
  Activity,
  CheckCircle2,
  Circle
} from "lucide-react";
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } from "recharts";

interface StatusOverviewProps {
  data: {
    backlog: number;
    todo: number;
    inProgress: number;
    inReview: number;
    done: number;
  };
}

export const StatusOverview = ({ data }: StatusOverviewProps) => {
  const total = data.backlog + data.todo + data.inProgress + data.inReview + data.done;
  
  const statusData = [
    { name: "Backlog", value: data.backlog, color: "#9CA3AF" },
    { name: "To Do", value: data.todo, color: "#6B7280" },
    { name: "In Progress", value: data.inProgress, color: "#3B82F6" },
    { name: "In Review", value: data.inReview, color: "#F59E0B" },
    { name: "Done", value: data.done, color: "#10B981" },
  ].filter(item => item.value > 0);

  const statusIcons = {
    "Backlog": Circle,
    "To Do": Circle,
    "In Progress": Clock,
    "In Review": AlertCircle,
    "Done": CheckCircle2,
  };
  
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <BarChart3 className="h-5 w-5" />
          Status overview
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          Get a snapshot of the status of your work items
        </p>
      </CardHeader>
      <CardContent>
        {total === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            <BarChart3 className="h-8 w-8 mx-auto mb-2 opacity-50" />
            <p className="text-sm">No tasks found</p>
          </div>
        ) : (
          <div className="space-y-4">
            {/* Donut Chart */}
            <div className="h-48">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={statusData}
                    cx="50%"
                    cy="50%"
                    innerRadius={40}
                    outerRadius={70}
                    paddingAngle={2}
                    dataKey="value"
                  >
                    {statusData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip 
                    formatter={(value: number) => [`${value} tasks`, '']}
                    labelFormatter={(label) => label}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>

            {/* Legend */}
            <div className="space-y-2">
              {statusData.map((item) => {
                const Icon = statusIcons[item.name as keyof typeof statusIcons];
                return (
                  <div key={item.name} className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div 
                        className="w-3 h-3 rounded-full" 
                        style={{ backgroundColor: item.color }}
                      />
                      <span className="text-sm font-medium">{item.name}</span>
                    </div>
                    <span className="text-sm font-medium">
                      {item.value} ({Math.round((item.value / total) * 100)}%)
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
};

interface RecentActivityProps {
  activities: Array<{
    id: string;
    user: string;
    action: string;
    target: string;
    time: string;
    status?: string;
    taskId?: string;
    workspaceId?: string;
    type: "created" | "updated" | "status_change" | "assigned" | "completed";
  }>;
  onActivityClick?: (activity: any) => void;
}

export const RecentActivity = ({ activities, onActivityClick }: RecentActivityProps) => {
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Activity className="h-5 w-5" />
          Recent activity
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          Stay up to date with what's happening across the project.
        </p>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {activities.slice(0, 6).map((activity) => (
            <div 
              key={activity.id} 
              className={`flex items-start gap-3 p-2 rounded-md transition-colors ${
                onActivityClick ? 'cursor-pointer hover:bg-muted/50' : ''
              }`}
              onClick={() => onActivityClick?.(activity)}
            >
              <div className="flex-shrink-0 mt-1">
                <div className="h-2 w-2 bg-muted-foreground rounded-full" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm">
                  <span className="font-medium">{activity.user}</span> {activity.action}{" "}
                  <span className="font-medium">"{activity.target}"</span>
                  {activity.status && (
                    <Badge variant="secondary" className="ml-2 text-xs">
                      {activity.status}
                    </Badge>
                  )}
                </p>
                <p className="text-xs text-muted-foreground">{activity.time}</p>
              </div>
              {onActivityClick && (
                <ArrowRight className="h-4 w-4 text-muted-foreground opacity-50 flex-shrink-0 mt-0.5" />
              )}
            </div>
          ))}
          {activities.length === 0 && (
            <div className="text-center py-6 text-muted-foreground">
              <Activity className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p className="text-sm">No recent activity</p>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
};

interface PriorityBreakdownProps {
  data: {
    highest: number;
    high: number;
    medium: number;
    low: number;
    lowest: number;
  };
}

export const PriorityBreakdown = ({ data }: PriorityBreakdownProps) => {
  const total = data.highest + data.high + data.medium + data.low + data.lowest;
  const maxValue = Math.max(data.highest, data.high, data.medium, data.low, data.lowest);
  
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <BarChart3 className="h-5 w-5" />
          Priority breakdown
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          Get a holistic view of how your work is being prioritized. See what your team's been focusing on
        </p>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="grid grid-cols-5 gap-2 h-32">
            {[
              { label: "Highest", value: data.highest, color: "bg-gray-600" },
              { label: "High", value: data.high, color: "bg-gray-500" },
              { label: "Medium", value: data.medium, color: "bg-gray-400" },
              { label: "Low", value: data.low, color: "bg-gray-300" },
              { label: "Lowest", value: data.lowest, color: "bg-gray-200" },
            ].map((item) => (
              <div key={item.label} className="flex flex-col items-center">
                <div className="flex-1 flex items-end w-full">
                  <div
                    className={`w-full ${item.color} rounded-t`}
                    style={{
                      height: `${maxValue > 0 ? (item.value / maxValue) * 100 : 0}%`,
                      minHeight: item.value > 0 ? "4px" : "0px",
                    }}
                  ></div>
                </div>
                <div className="text-xs text-center mt-2">
                  <div className="font-medium">{item.value}</div>
                  <div className="text-muted-foreground">{item.label}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

interface TypesOfWorkProps {
  data: {
    task: number;
    epic: number;
    subtask: number;
  };
}

export const TypesOfWork = ({ data }: TypesOfWorkProps) => {
  const total = data.task + data.epic + data.subtask;
  
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <BarChart3 className="h-5 w-5" />
          Types of work
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          Get a breakdown of work items by their types. View all items
        </p>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {[
            { label: "Task", value: data.task, icon: "📋" },
            { label: "Epic", value: data.epic, icon: "⚡" },
            { label: "Subtask", value: data.subtask, icon: "📝" },
          ].map((item) => (
            <div key={item.label} className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span>{item.icon}</span>
                <span className="text-sm font-medium">{item.label}</span>
              </div>
              <div className="flex items-center gap-2">
                <Progress 
                  value={total > 0 ? (item.value / total) * 100 : 0} 
                  className="w-24" 
                />
                <span className="text-sm font-medium w-8 text-right">
                  {total > 0 ? Math.round((item.value / total) * 100) : 0}%
                </span>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
};

interface TeamWorkloadProps {
  members: Member[];
  tasks: Task[];
}

export const TeamWorkload = ({ members, tasks }: TeamWorkloadProps) => {
  const workloadData = members.map((member) => {
    // Fix: Compare task.assigneeId with member.id (not member.userId)
    const memberTasks = tasks.filter((task) => task.assigneeId === member.id);
    
    return {
      name: member.name || member.email,
      email: member.email,
      taskCount: memberTasks.length,
    };
  });

  const unassignedTasks = tasks.filter((task) => !task.assigneeId).length;
  const totalTasks = tasks.length;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Users className="h-5 w-5" />
          Team workload
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          Monitor the capacity of your team. Reassign work items to get the right balance
        </p>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {workloadData.map((member) => (
            <div key={member.email} className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
                  <span className="text-xs font-medium text-blue-600">
                    {(member.name || member.email).charAt(0).toUpperCase()}
                  </span>
                </div>
                <span className="text-sm font-medium">{member.name || member.email}</span>
              </div>
              <div className="flex items-center gap-2">
                <Progress 
                  value={totalTasks > 0 ? (member.taskCount / totalTasks) * 100 : 0} 
                  className="w-24" 
                />
                <span className="text-sm font-medium w-8 text-right">
                  {totalTasks > 0 ? Math.round((member.taskCount / totalTasks) * 100) : 0}%
                </span>
              </div>
            </div>
          ))}
          
          {unassignedTasks > 0 && (
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 bg-gray-100 rounded-full flex items-center justify-center">
                  <span className="text-xs font-medium text-gray-600">?</span>
                </div>
                <span className="text-sm font-medium">Unassigned</span>
              </div>
              <div className="flex items-center gap-2">
                <Progress 
                  value={totalTasks > 0 ? (unassignedTasks / totalTasks) * 100 : 0} 
                  className="w-24" 
                />
                <span className="text-sm font-medium w-8 text-right">
                  {totalTasks > 0 ? Math.round((unassignedTasks / totalTasks) * 100) : 0}%
                </span>
              </div>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}; 