import { motion, Variants } from "framer-motion";
import { Users, CheckSquare, FileText, TrendingUp, Activity, Clock, ChevronRight } from "lucide-react";
import { DASHBOARD_STATS, MOCK_ACTIVITY, MOCK_TASKS, USER_PERFORMANCE } from "@/data/mockData";
import { StatusBadge } from "@/components/shared/StatusBadge";
import { PriorityBadge } from "@/components/shared/PriorityBadge";
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Legend } from "recharts";
import { useLocation } from "wouter";

const fadeUp: Variants = {
  hidden: { opacity: 0, y: 16 },
  show: (i: number) => ({ 
    opacity: 1, 
    y: 0, 
    transition: { delay: i * 0.07, duration: 0.4, ease: "easeOut" } 
  }),
};

const statCards = [
  { label: "Total Users", value: DASHBOARD_STATS.totalUsers, sub: `${DASHBOARD_STATS.activeUsers} active`, icon: Users, color: "bg-blue-50 text-blue-600" },
  { label: "Total Tasks", value: DASHBOARD_STATS.totalTasks, sub: `${DASHBOARD_STATS.completedTasks} completed`, icon: CheckSquare, color: "bg-emerald-50 text-emerald-600" },
  { label: "In Progress", value: DASHBOARD_STATS.inProgressTasks, sub: `${DASHBOARD_STATS.pendingTasks} pending`, icon: TrendingUp, color: "bg-amber-50 text-amber-600" },
  { label: "Documents", value: DASHBOARD_STATS.totalDocuments, sub: "Uploaded files", icon: FileText, color: "bg-indigo-50 text-indigo-600" },
];

const taskStatusData = [
  { name: "Completed", value: DASHBOARD_STATS.completedTasks, color: "#10b981" },
  { name: "In Progress", value: DASHBOARD_STATS.inProgressTasks, color: "#3b82f6" },
  { name: "Pending", value: DASHBOARD_STATS.pendingTasks, color: "#f59e0b" },
];

const priorityData = [
  { name: "High", value: DASHBOARD_STATS.tasksByPriority.high, fill: "#f43f5e" },
  { name: "Medium", value: DASHBOARD_STATS.tasksByPriority.medium, fill: "#f59e0b" },
  { name: "Low", value: DASHBOARD_STATS.tasksByPriority.low, fill: "#64748b" },
];

function getActionIcon(action: string) {
  switch (action) {
    case "created": return <div className="w-2 h-2 rounded-full bg-blue-500" />;
    case "completed": return <div className="w-2 h-2 rounded-full bg-emerald-500" />;
    case "updated": return <div className="w-2 h-2 rounded-full bg-amber-500" />;
    case "uploaded": return <div className="w-2 h-2 rounded-full bg-indigo-500" />;
    default: return <div className="w-2 h-2 rounded-full bg-gray-400" />;
  }
}

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const h = Math.floor(diff / 3600000);
  const d = Math.floor(h / 24);
  if (d > 0) return `${d}d ago`;
  if (h > 0) return `${h}h ago`;
  return "Just now";
}

export default function DashboardPage() {
  const [, setLocation] = useLocation();
  const recentTasks = MOCK_TASKS.filter(t => t.status !== "completed").slice(0, 4);

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Dashboard</h1>
        <p className="text-sm text-muted-foreground mt-1">Welcome back, Alex. Here's what's happening today.</p>
      </div>

      {/* Stat cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card, i) => (
          <motion.div key={card.label} custom={i} initial="hidden" animate="show" variants={fadeUp}
            className="bg-card border border-card-border rounded-xl p-5 shadow-sm"
          >
            <div className="flex items-start justify-between">
              <div>
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">{card.label}</p>
                <p className="text-3xl font-bold text-foreground mt-1">{card.value}</p>
                <p className="text-xs text-muted-foreground mt-1">{card.sub}</p>
              </div>
              <div className={`p-2.5 rounded-lg ${card.color}`}>
                <card.icon className="w-5 h-5" />
              </div>
            </div>
          </motion.div>
        ))}
      </div>

      {/* Overall progress */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.3 }}
        className="bg-card border border-card-border rounded-xl p-6 shadow-sm"
      >
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-semibold text-foreground">Overall Task Completion</h2>
          <span className="text-2xl font-bold text-blue-600">{DASHBOARD_STATS.overallCompletionPercent}%</span>
        </div>
        <div className="h-3 bg-muted rounded-full overflow-hidden">
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: `${DASHBOARD_STATS.overallCompletionPercent}%` }}
            transition={{ duration: 1, delay: 0.5, ease: "easeOut" }}
            className="h-full bg-gradient-to-r from-blue-500 to-indigo-500 rounded-full"
          />
        </div>
        <div className="flex items-center gap-6 mt-3 text-xs text-muted-foreground">
          <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-emerald-500 inline-block" />{DASHBOARD_STATS.completedTasks} Completed</span>
          <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-blue-500 inline-block" />{DASHBOARD_STATS.inProgressTasks} In Progress</span>
          <span className="flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-amber-500 inline-block" />{DASHBOARD_STATS.pendingTasks} Pending</span>
        </div>
      </motion.div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.35 }}
          className="bg-card border border-card-border rounded-xl p-6 shadow-sm"
        >
          <h2 className="text-sm font-semibold text-foreground mb-4">Task Status Distribution</h2>
          <ResponsiveContainer width="100%" height={200}>
            <PieChart>
              <Pie data={taskStatusData} cx="50%" cy="50%" innerRadius={55} outerRadius={80} paddingAngle={3} dataKey="value">
                {taskStatusData.map((entry, i) => (
                  <Cell key={i} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip formatter={(v: any) => [v, "Tasks"]} />
              <Legend iconType="circle" iconSize={8} formatter={(v) => <span className="text-xs text-muted-foreground">{v}</span>} />
            </PieChart>
          </ResponsiveContainer>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.4 }}
          className="bg-card border border-card-border rounded-xl p-6 shadow-sm"
        >
          <h2 className="text-sm font-semibold text-foreground mb-4">Priority Distribution</h2>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={priorityData} margin={{ top: 5, right: 10, left: -20, bottom: 5 }}>
              <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fontSize: 12 }} />
              <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 11 }} />
              <Tooltip cursor={{ fill: "hsl(var(--muted))" }} />
              <Bar dataKey="value" radius={[4, 4, 0, 0]}>
                {priorityData.map((entry, i) => (
                  <Cell key={i} fill={entry.fill} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </motion.div>
      </div>

      {/* Bottom row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Recent activity */}
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.45 }}
          className="lg:col-span-1 bg-card border border-card-border rounded-xl p-6 shadow-sm"
        >
          <div className="flex items-center gap-2 mb-4">
            <Activity className="w-4 h-4 text-muted-foreground" />
            <h2 className="text-sm font-semibold text-foreground">Recent Activity</h2>
          </div>
          <div className="space-y-3">
            {MOCK_ACTIVITY.slice(0, 7).map(a => (
              <div key={a.id} className="flex items-start gap-3">
                <div className="mt-1.5 flex-shrink-0">{getActionIcon(a.action)}</div>
                <div className="flex-1 min-w-0">
                  <p className="text-xs text-foreground leading-snug">
                    <span className="font-medium">{a.userName}</span>{" "}
                    <span className="text-muted-foreground">{a.action}</span>{" "}
                    <span className="font-medium truncate">{a.entityTitle}</span>
                  </p>
                  <p className="text-xs text-muted-foreground mt-0.5 flex items-center gap-1">
                    <Clock className="w-3 h-3" />{timeAgo(a.createdAt)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </motion.div>

        {/* Active tasks */}
        <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5 }}
          className="lg:col-span-2 bg-card border border-card-border rounded-xl p-6 shadow-sm"
        >
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-foreground">Active Tasks</h2>
            <button onClick={() => setLocation("/tasks")} className="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
              View all <ChevronRight className="w-3 h-3" />
            </button>
          </div>
          <div className="space-y-3">
            {recentTasks.map(task => (
              <div key={task.id} className="p-3 bg-muted/40 rounded-lg border border-border/50">
                <div className="flex items-start justify-between gap-2 mb-2">
                  <p className="text-sm font-medium text-foreground leading-snug">{task.title}</p>
                  <div className="flex gap-1.5 flex-shrink-0">
                    <StatusBadge status={task.status} />
                    <PriorityBadge priority={task.priority} />
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                    <div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${task.completionPercent}%` }} />
                  </div>
                  <span className="text-xs text-muted-foreground font-medium w-8 text-right">{task.completionPercent}%</span>
                </div>
                {task.assignedUserName && (
                  <p className="text-xs text-muted-foreground mt-1.5">Assigned to {task.assignedUserName}</p>
                )}
              </div>
            ))}
          </div>
        </motion.div>
      </div>

      {/* User performance */}
      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.55 }}
        className="bg-card border border-card-border rounded-xl shadow-sm overflow-hidden"
      >
        <div className="px-6 py-4 border-b border-border">
          <h2 className="text-sm font-semibold text-foreground">Team Performance</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="text-left px-6 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Name</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Role</th>
                <th className="text-center px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Assigned</th>
                <th className="text-center px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Completed</th>
                <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Performance</th>
              </tr>
            </thead>
            <tbody>
              {USER_PERFORMANCE.map((u, i) => (
                <tr key={u.userId} className={i < USER_PERFORMANCE.length - 1 ? "border-b border-border/50" : ""}>
                  <td className="px-6 py-3 font-medium text-foreground">
                    <div className="flex items-center gap-3">
                      <div className="w-7 h-7 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white text-xs font-bold flex-shrink-0">
                        {u.name.split(" ").map(n => n[0]).join("").slice(0, 2)}
                      </div>
                      {u.name}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-muted-foreground capitalize">{u.role.replace("_", " ")}</td>
                  <td className="px-4 py-3 text-center">{u.tasksAssigned}</td>
                  <td className="px-4 py-3 text-center">{u.tasksCompleted}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden max-w-24">
                        <div
                          className={`h-full rounded-full ${u.performancePercent >= 80 ? "bg-emerald-500" : u.performancePercent >= 50 ? "bg-amber-500" : "bg-rose-500"}`}
                          style={{ width: `${u.performancePercent}%` }}
                        />
                      </div>
                      <span className="text-xs font-medium text-muted-foreground">{u.performancePercent}%</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </motion.div>
    </div>
  );
}
