"use client";
import React, { useState, useEffect } from "react";
import { apiGet } from "@/lib/axios";
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, Legend, ResponsiveContainer,
  PieChart, Pie, Cell, LineChart, Line, AreaChart, Area
} from "recharts";
import { useAppSelector } from "@/store/hooks";
import { Activity, Users, FolderKanban, CheckCircle2, Clock, AlertTriangle } from "lucide-react";
import Link from "next/link";
import DataTable from "react-data-table-component";

export default function AnalyticsAndReportsPage() {
  const projects = useAppSelector((state) => state.projects.projects);
  const tasks = useAppSelector((state) => state.tasks.tasks);
  const team = useAppSelector((state) => state.team.members);
  const reports = useAppSelector((state) => state.reports.reports);
  const [activeTab, setActiveTab] = useState<"projects" | "developers" | "team" | "activity">("projects");

  const [rowsPerPage, setRowsPerPage] = useState(10);

  const [apiProjectData, setApiProjectData] = useState<any>(null);
  const [apiDeveloperData, setApiDeveloperData] = useState<any>(null);
  const [apiTeamData, setApiTeamData] = useState<any>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        if (activeTab === 'projects') {
          const res = await apiGet<any>('/api/reports/projects');
          if (res?.success) setApiProjectData(res.data);
        } else if (activeTab === 'developers') {
          const res = await apiGet<any>('/api/reports/developers');
          if (res?.success) setApiDeveloperData(res.data);
        } else if (activeTab === 'team') {
          const res = await apiGet<any>('/api/reports/team');
          if (res?.success) setApiTeamData(res.data);
        }
      } catch (err) {
        console.error('Error fetching analytics data:', err);
      }
    };
    fetchData();
  }, [activeTab]);

  // Colors for charts
  const COLORS = ['#22C55E', '#2563EB', '#f59e0b', '#ef4444', '#8b5cf6'];
  const COLORS_ALT = ['#2563EB', '#b446e5', '#F59E0B', '#f97316', '#eab308'];

  // --- Project Stats Calculations ---
  const completedProjects = apiProjectData?.overallProgress?.completed ?? projects.filter(p => p.status === 'COMPLETED').length;
  const activeProjects = apiProjectData?.overallProgress?.active ?? projects.filter(p => p.status === 'ACTIVE').length;
  const delayedProjects = apiProjectData?.delayedItems?.delayedProjectsCount ?? projects.filter(p => p.status === 'DELAYED').length;
  const totalProjectsCount = apiProjectData?.summary?.totalProjects ?? projects.length;
  const teamMembersCount = apiProjectData?.summary?.teamMembers ?? team.length;

  const projectStatusData = [
    { name: 'Active', value: activeProjects },
    { name: 'Completed', value: completedProjects },
    { name: 'Delayed', value: delayedProjects },
    { name: 'On Hold', value: apiProjectData?.overallProgress?.others ?? projects.filter(p => p.status === 'ON_HOLD').length },
  ];

  const milestoneData = [
    { name: 'Completed', value: apiProjectData?.milestoneCompletion?.completed ?? 45 },
    { name: 'In Progress', value: apiProjectData?.milestoneCompletion?.inProgress ?? 30 },
    { name: 'Pending', value: apiProjectData?.milestoneCompletion?.pending ?? 25 },
  ];

  const sprintProgressData = apiProjectData?.sprintProgress ?? [
    { name: 'Sprint 1', progress: 100 },
    { name: 'Sprint 2', progress: 100 },
    { name: 'Sprint 3', progress: 65 },
    { name: 'Sprint 4', progress: 0 },
  ];

  // --- Task Stats Calculations ---
  const completedTasks = apiProjectData?.summary?.tasksCompleted ?? tasks.filter(t => t.status === 'COMPLETED').length;
  const pendingTasks = apiProjectData?.completedVsPendingTasks?.pending ?? tasks.filter(t => t.status !== 'COMPLETED').length;
  const blockedTasks = apiProjectData?.completedVsPendingTasks?.blocked ?? tasks.filter(t => t.status === 'BLOCKED').length;

  const taskProgressData = [
    { name: 'Completed', value: completedTasks },
    { name: 'Pending', value: pendingTasks },
    { name: 'Blocked', value: blockedTasks },
  ];

  // --- Developer Productivity Mock Data ---
  let developerData: any[] = [];
  if (apiDeveloperData?.developerPerformanceMatrix?.length > 0) {
    developerData = apiDeveloperData.developerPerformanceMatrix.map((dev: any) => ({
      name: dev.developerName,
      loggedHours: dev.hoursWorked,
      estimatedHours: apiDeveloperData.developerHoursChart.find((d: any) => d.developerName === dev.developerName)?.estimatedHours || 0,
      completedTasks: dev.tasksCompleted,
      pendingTasks: dev.pendingTasks,
      productivityScore: dev.productivityPercentage
    }));
  } else {
    developerData = team.map(member => {
      const userTasks = tasks.filter(t => t.assignees.includes(member.id));
      const userReports = reports.filter(r => r.userId === member.id);
      const totalHoursLogged = userReports.reduce((acc, curr) => acc + curr.hoursWorked, 0);
      const totalEstHours = userTasks.reduce((acc, curr) => acc + curr.estimatedHours, 0);
      const completedTasksCount = userTasks.filter(t => t.status === 'COMPLETED').length;
      const pendingTasksCount = userTasks.filter(t => t.status !== 'COMPLETED').length;

      return {
        name: member.name,
        loggedHours: totalHoursLogged || Math.floor(Math.random() * 40),
        estimatedHours: totalEstHours || Math.floor(Math.random() * 40) + 10,
        completedTasks: completedTasksCount || Math.floor(Math.random() * 10),
        pendingTasks: pendingTasksCount || Math.floor(Math.random() * 5),
        productivityScore: Math.floor(Math.random() * 40) + 60,
      };
    });

    if (developerData.length === 0) {
      developerData = [
        { name: "Deepak Saini", loggedHours: 38, estimatedHours: 40, completedTasks: 12, pendingTasks: 2, productivityScore: 92 },
        { name: "Ananya Sharma", loggedHours: 42, estimatedHours: 35, completedTasks: 15, pendingTasks: 1, productivityScore: 95 },
        { name: "Rahul Verma", loggedHours: 28, estimatedHours: 30, completedTasks: 8, pendingTasks: 5, productivityScore: 75 },
        { name: "Priya Singh", loggedHours: 35, estimatedHours: 45, completedTasks: 10, pendingTasks: 4, productivityScore: 82 },
        { name: "Vikram Patel", loggedHours: 40, estimatedHours: 40, completedTasks: 11, pendingTasks: 3, productivityScore: 88 },
      ];
    }
  }

  // --- Team Metrics ---
  const workloadData = apiTeamData?.workloadDistribution?.map((w: any) => ({ role: w.developerName, tasks: w.taskCount })) ?? [
    { role: 'Frontend', tasks: 45 },
    { role: 'Backend', tasks: 38 },
    { role: 'Design', tasks: 20 },
    { role: 'QA', tasks: 15 },
  ];

  const teamProductivityData = apiTeamData?.teamProductivityScore ?? [
    { week: 'W1', score: 75 },
    { week: 'W2', score: 82 },
    { week: 'W3', score: 88 },
    { week: 'W4', score: 85 },
  ];

  const velocityData = apiTeamData?.sprintVelocity?.map((s: any) => ({ sprint: s.sprintName, points: s.actualVelocity, expected: s.expectedCapacity })) ?? [
    { sprint: 'Sprint 1', points: 45, expected: 50 },
    { sprint: 'Sprint 2', points: 52, expected: 50 },
    { sprint: 'Sprint 3', points: 38, expected: 45 },
    { sprint: 'Sprint 4', points: 60, expected: 55 },
  ];

  const devColumns = [
    {
      name: "Developer",
      selector: (row: any) => row.name,
      sortable: true,
      cell: (row: any) => <div data-th="Developer" className="mobile-cell"><div className="md:font-medium text-gray-600 md:text-gray-800">{row.name}</div></div>
    },
    {
      name: "Tasks Completed",
      selector: (row: any) => row.completedTasks,
      sortable: true,
      cell: (row: any) => <div data-th="Tasks Completed" className="mobile-cell"><span className="text-gray-600">{row.completedTasks} tasks</span></div>
    },
    {
      name: "Pending Tasks",
      selector: (row: any) => row.pendingTasks,
      sortable: true,
      cell: (row: any) => <div data-th="Pending Tasks" className="mobile-cell"><span className="text-gray-600">{row.pendingTasks} tasks</span></div>
    },
    {
      name: "Hours Worked",
      selector: (row: any) => row.loggedHours,
      sortable: true,
      cell: (row: any) => <div data-th="Hours Worked" className="mobile-cell"><span className="text-gray-600">{row.loggedHours} hrs</span></div>
    },
    {
      name: "Productivity",
      selector: (row: any) => row.productivityScore,
      sortable: true,
      cell: (row: any) => (
        <div data-th="Productivity" className="mobile-cell w-full">
          <div className="flex items-center gap-2 w-full">
            <div className="w-full bg-gray-200 rounded-full h-2 max-w-[100px]">
              <div className={`h-2 rounded-full ${row.productivityScore > 80 ? 'bg-green-500' : row.productivityScore > 60 ? 'bg-blue-500' : 'bg-orange-500'}`} style={{ width: `${row.productivityScore}%` }}></div>
            </div>
            <span className="text-xs font-medium text-gray-600">{row.productivityScore}%</span>
          </div>
        </div>
      )
    }
  ];

  return (
    <div className="min-h-screen">
      <div className="mx-auto max-w-[1500px] space-y-6">
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Reports & Analytics</h1>
        </div>

        {/* Global KPIs */}
        <div className="rounded-xl bg-white md:p-6 xl:px-0 xl:py-6 shadow-theme-md">
          <div className="grid md:grid-cols-2 xl:grid-cols-4 px-6 md:px-0">
            <div className="flex items-center gap-2 justify-between py-4 xl:py-0 md:px-4 xl:px-6 border-b xl:border-b-0 md:border-r border-gray-200">
              <div>
                <span className="mb-2 text-lg lg:text-xl text-gray-500 font-normal block">Total Projects</span>
                <h3 className="text-3xl font-semibold text-brand-950">{totalProjectsCount}</h3>
              </div>
              <div className={`flex h-[60px] w-[60px] shrink-0 items-center justify-center rounded-full bg-[#6cd406]/10`}>
                <FolderKanban className="w-6 h-6 text-[#6cd406]" />
              </div>
            </div>

            <div className="flex items-center gap-2 justify-between py-4 xl:py-0 md:px-4 xl:px-6 border-b xl:border-b-0 xl:border-r border-gray-200">
              <div>
                <span className="mb-2 text-lg lg:text-xl text-gray-500 font-normal block">Tasks Completed</span>
                <h3 className="text-3xl font-semibold text-brand-950">{completedTasks}</h3>
              </div>
              <div className={`flex h-[60px] w-[60px] shrink-0 items-center justify-center rounded-full bg-[#2563EB]/10`}>
                <CheckCircle2 className="w-6 h-6 text-[#2563EB]" />
              </div>
            </div>

            <div className="flex items-center gap-2 justify-between py-4 xl:py-0 md:px-4 xl:px-6 border-b md:border-b-0 md:border-r border-gray-200">
              <div>
                <span className="mb-2 text-lg lg:text-xl text-gray-500 font-normal block">Team Members</span>
                <h3 className="text-3xl font-semibold text-brand-950">{teamMembersCount}</h3>
              </div>
              <div className={`flex h-[60px] w-[60px] shrink-0 items-center justify-center rounded-full bg-cyan-100`}>
                <Users className="w-6 h-6 text-cyan-600" />
              </div>
            </div>

            <div className="flex items-center gap-2 justify-between py-4 xl:py-0 md:px-4 xl:px-6">
              <div>
                <span className="mb-2 text-lg lg:text-xl text-gray-500 font-normal block">Delayed Items</span>
                <h3 className="text-3xl font-semibold text-brand-950">{delayedProjects + blockedTasks}</h3>
              </div>
              <div className={`flex h-[60px] w-[60px] shrink-0 items-center justify-center rounded-full bg-[#EF4444]/10`}>
                <Clock className="w-6 h-6 text-[#EF4444]" />
              </div>
            </div>
          </div>
        </div>

        {/* Tab Navigation */}
        <div className="rounded-xl bg-white p-6 shadow-theme-md">
          <div className="flex flex-wrap rounded-lg bg-gray-100 gap-2 p-1 mb-5">
            {(["projects", "developers", "team"] as const).map((tab) => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className={`text-base font-medium transition-colors relative px-4 py-2 rounded-md w-full sm:w-auto ${activeTab === tab ? "text-brand-950 bg-white shadow-sm" : "text-gray-500 bg-transparent hover:bg-gray-200/50"
                  }`}
              >
                {tab.charAt(0).toUpperCase() + tab.slice(1)} Reports
              </button>
            ))}
          </div>

          {activeTab === "projects" && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 animate-in fade-in duration-300">
              {/* Overall Progress (Project Status) */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Overall Progress (Projects)</h3>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie data={projectStatusData.filter(d => d.value > 0)} cx="50%" cy="50%" innerRadius={60} outerRadius={100} paddingAngle={5} dataKey="value">
                        {projectStatusData.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />)}
                      </Pie>
                      <RechartsTooltip />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Completed vs Pending Tasks */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Completed vs Pending Tasks</h3>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={taskProgressData} margin={{ top: 20, right: 30, left: 0, bottom: 5 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" />
                      <XAxis dataKey="name" axisLine={false} tickLine={false} />
                      <YAxis axisLine={false} tickLine={false} />
                      <RechartsTooltip cursor={{ fill: '#f3f4f6' }} />
                      <Bar dataKey="value" radius={[4, 4, 0, 0]}>
                        {taskProgressData.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />)}
                      </Bar>
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Milestone Completion */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Milestone Completion</h3>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie data={milestoneData} cx="50%" cy="50%" outerRadius={100} dataKey="value" label>
                        {milestoneData.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS_ALT[index % COLORS_ALT.length]} />)}
                      </Pie>
                      <RechartsTooltip />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Sprint Progress */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Sprint Progress (%)</h3>
                <div className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <AreaChart data={sprintProgressData} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} />
                      <XAxis dataKey="name" axisLine={false} tickLine={false} />
                      <YAxis axisLine={false} tickLine={false} />
                      <RechartsTooltip />
                      <Area type="monotone" dataKey="progress" stroke="#8B5CF6" fill="#c4b5fd" />
                    </AreaChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Delayed Items Overview */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6 col-span-1 lg:col-span-2">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Delayed Items</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="bg-[#EF4444]/10 border border-orange-100 rounded-lg p-5">
                    <p className="text-sm font-medium text-[#EF4444] mb-1">Delayed Projects</p>
                    <h4 className="text-3xl font-bold text-[#EF4444]">{delayedProjects}</h4>
                    <p className="text-xs text-orange-700 mt-2">Projects that missed their deadline.</p>
                  </div>
                  <div className="bg-[#DC2626]/10 border border-red-100 rounded-lg p-5">
                    <p className="text-sm font-medium text-[#DC2626] mb-1">Blocked / Delayed Tasks</p>
                    <h4 className="text-3xl font-bold text-[#DC2626]">{blockedTasks}</h4>
                    <p className="text-xs text-red-700 mt-2">Tasks currently stuck or overdue.</p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === "developers" && (
            <div className="grid grid-cols-1 gap-6 animate-in fade-in duration-300">
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Developer Hours: Worked vs Estimated</h3>
                <div className="h-[400px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={developerData} margin={{ top: 20, right: 30, left: 0, bottom: 5 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e3e8f3" />
                      <XAxis dataKey="name" axisLine={false} tickLine={false} />
                      <YAxis axisLine={false} tickLine={false} />
                      <RechartsTooltip cursor={{ fill: '#f3f4f6' }} />
                      <Legend />
                      <Bar dataKey="loggedHours" name="Hours Worked" fill="#25395c" radius={[4, 4, 0, 0]} />
                      <Bar dataKey="estimatedHours" name="Estimated Hours" fill="#e3e8f3" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>

              <div className="md:border border-gray-200 md:rounded-lg">
                <div className="flex items-center justify-between md:border-b md:px-4 pb-4 md:py-4">
                  <h3 className="text-lg lg:text-xl font-medium text-brand-950">Developer Performance Matrix</h3>
                  <div className="hidden md:flex items-center gap-2">
                    <span className="text-sm font-normal text-gray-500 block">Show</span>
                    <div className="relative">
                      <select
                        value={rowsPerPage}
                        onChange={(e) => setRowsPerPage(Number(e.target.value))}
                        className="w-full rounded-lg border appearance-none px-3 py-2 pr-8 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                      >
                        <option value={10}>10</option>
                        <option value={25}>25</option>
                        <option value={50}>50</option>
                        <option value={100}>100</option>
                      </select>
                      <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-2 top-1/2">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24">
                          <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 9l6 6 6-6"></path>
                        </svg>
                      </span>
                    </div>
                    <span className="text-sm font-normal text-gray-500">entries</span>
                  </div>
                </div>

                <div className="overflow-x-auto">
                  <DataTable
                    columns={devColumns}
                    data={developerData}
                    pagination
                    paginationPerPage={rowsPerPage}
                    paginationComponentOptions={{ noRowsPerPage: true }}
                    highlightOnHover
                    customStyles={{
                  headRow: {
                    style: {
                      backgroundColor: '#ffffff',
                      color: '#1E293B',
                      fontWeight: 600,
                      fontSize: '14px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                  rows: {
                    style: {
                      fontSize: '14px',
                      color: '#475569',
                      minHeight: '60px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                }}
                  />
                </div>
              </div>
            </div>
          )}

          {activeTab === "team" && (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 animate-in fade-in duration-300">
              {/* Workload Distribution */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Workload Distribution</h3>
                <div className="h-[350px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie data={workloadData} cx="50%" cy="50%" innerRadius={60} outerRadius={100} paddingAngle={5} dataKey="tasks">
                        {workloadData?.map((entry: any, index: any) => <Cell key={`cell-${index}`} fill={COLORS_ALT[index % COLORS_ALT.length]} />)}
                      </Pie>
                      <RechartsTooltip />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Team Productivity */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Team Productivity Score</h3>
                <div className="h-[350px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={teamProductivityData} margin={{ top: 20, right: 30, left: 0, bottom: 5 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" />
                      <XAxis dataKey="week" axisLine={false} tickLine={false} />
                      <YAxis axisLine={false} tickLine={false} domain={[0, 100]} />
                      <RechartsTooltip />
                      <Line type="monotone" dataKey="score" name="Productivity %" stroke="#10b981" strokeWidth={3} activeDot={{ r: 8 }} />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Sprint Velocity */}
              <div className="p-5 border border-gray-200 rounded-lg lg:p-6 col-span-1 lg:col-span-2">
                <h3 className="mb-4 lg:mb-6 text-lg lg:text-xl font-medium text-brand-950">Sprint Velocity</h3>
                <div className="h-[350px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={velocityData} margin={{ top: 20, right: 30, left: 0, bottom: 5 }}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" />
                      <XAxis dataKey="sprint" axisLine={false} tickLine={false} />
                      <YAxis axisLine={false} tickLine={false} />
                      <RechartsTooltip />
                      <Legend />
                      <Line type="monotone" dataKey="points" name="Actual Velocity (Points)" stroke="#3b82f6" strokeWidth={3} activeDot={{ r: 8 }} />
                      <Line type="monotone" dataKey="expected" name="Expected Capacity (Points)" stroke="#9ca3af" strokeWidth={2} strokeDasharray="5 5" />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

