/**
 * Admin Analytics Section Component
 * Displays Active Levels, Collaboration, and Department Stats
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Activity, MessageSquare, PieChart, Download } from 'lucide-react';
import { DashboardKPIs, DepartmentStats, UpcomingDeadline, DateRange } from '@/services/dashboard.service';
import { CriticalRequest } from '@/services/dashboard.service';
import type { CriticalAlertData } from '@/components/dashboard/CriticalAlertCard';
import { ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
import { KPIClickFilters } from '../../components/types/dashboard.types';

interface AdminAnalyticsSectionProps {
  kpis: DashboardKPIs | null;
  upcomingDeadlines: UpcomingDeadline[];
  criticalRequests: (CriticalRequest | CriticalAlertData)[];
  departmentStats: DepartmentStats[];
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  exportingDeptStats: boolean;
  onKPIClick: (filters: KPIClickFilters) => void;
  onExportDepartmentStats: (dateRange: DateRange, startDate?: Date, endDate?: Date) => void;
}

export function AdminAnalyticsSection({
  kpis,
  upcomingDeadlines,
  criticalRequests,
  departmentStats,
  dateRange,
  customStartDate,
  customEndDate,
  exportingDeptStats,
  onKPIClick,
  onExportDepartmentStats,
}: AdminAnalyticsSectionProps) {
  if (!kpis) return null;

  const getFilterParams = () => ({
    dateRange,
    startDate: customStartDate,
    endDate: customEndDate,
  });

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6" data-testid="admin-analytics-section">
      {/* Left Side: Active Levels and Collaboration stacked - 1/3 width */}
      <div className="flex flex-col gap-4 sm:gap-6 lg:col-span-1">
        {/* Active Levels */}
        <Card className="shadow-md hover:shadow-lg transition-shadow flex-1" data-testid="active-levels-card">
          <CardHeader className="pb-3">
            <div className="flex items-center gap-2">
              <div className="p-2 bg-blue-100 rounded-lg">
                <Activity className="h-4 w-4 text-blue-600" />
              </div>
              <CardTitle className="text-sm">Active Levels</CardTitle>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-baseline gap-2">
                <span className="text-2xl sm:text-3xl font-bold text-blue-600">{upcomingDeadlines.length}</span>
                <span className="text-xs text-muted-foreground">levels</span>
              </div>
              <Separator />
              <div className="space-y-1 text-xs">
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">Avg Time/Level</span>
                  <span className="font-semibold">
                    {upcomingDeadlines.length > 0
                      ? (kpis.tatEfficiency.avgCycleTimeHours / upcomingDeadlines.length).toFixed(1)
                      : '0'}
                    h
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">At Risk</span>
                  <span className="font-semibold text-red-600">
                    {criticalRequests.filter((r) => r.breachCount > 0).length}
                  </span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Collaboration */}
        <Card className="shadow-md hover:shadow-lg transition-shadow flex-1" data-testid="collaboration-card">
          <CardHeader className="pb-3">
            <div className="flex items-center gap-2">
              <div className="p-2 bg-indigo-100 rounded-lg">
                <MessageSquare className="h-4 w-4 text-indigo-600" />
              </div>
              <CardTitle className="text-sm">Collaboration</CardTitle>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="grid grid-cols-2 gap-2">
                <div className="text-center p-2 bg-indigo-50 rounded">
                  <p className="text-xs text-muted-foreground">Notes</p>
                  <p className="text-lg sm:text-xl font-bold text-indigo-600">{kpis.engagement.workNotesAdded}</p>
                </div>
                <div className="text-center p-2 bg-purple-50 rounded">
                  <p className="text-xs text-muted-foreground">Files</p>
                  <p className="text-lg sm:text-xl font-bold text-purple-600">
                    {kpis.engagement.attachmentsUploaded}
                  </p>
                </div>
              </div>
              <Separator />
              <div className="text-xs text-muted-foreground text-center">
                {kpis.requestVolume.totalRequests > 0
                  ? (kpis.engagement.workNotesAdded / kpis.requestVolume.totalRequests).toFixed(1)
                  : '0'}{' '}
                avg notes per request
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Right Side: Department-wise Workflow Summary - Full height - 2/3 width */}
      {departmentStats.length > 0 && (
        <Card className="shadow-md hover:shadow-lg transition-shadow lg:col-span-2" data-testid="department-stats-card">
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div className="flex items-center gap-3">
                <div className="bg-blue-50 p-2 sm:p-3 rounded-lg">
                  <PieChart className="h-5 w-5 sm:h-6 sm:w-6 text-blue-600" />
                </div>
                <div>
                  <CardTitle className="text-base sm:text-lg lg:text-xl">Department-wise Workflow Summary</CardTitle>
                  <CardDescription className="text-xs sm:text-sm">
                    Workflow distribution across departments
                  </CardDescription>
                </div>
              </div>
              <Button
                variant="outline"
                size="sm"
                className="gap-2 self-start sm:self-auto"
                onClick={() => onExportDepartmentStats(dateRange, customStartDate, customEndDate)}
                disabled={exportingDeptStats}
                data-testid="export-dept-stats-button"
              >
                <Download className={`w-3 h-3 sm:w-4 sm:h-4 ${exportingDeptStats ? 'animate-pulse' : ''}`} />
                <span className="text-xs sm:text-sm">{exportingDeptStats ? 'Exporting...' : 'Export'}</span>
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart data={departmentStats}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis
                  dataKey="department"
                  stroke="#999"
                  tick={(props) => {
                    const { x, y, payload } = props;
                    return (
                      <g transform={`translate(${x},${y})`}>
                        <text
                          x={0}
                          y={0}
                          dy={16}
                          textAnchor="middle"
                          fill="#999"
                          fontSize={11}
                          className="cursor-pointer hover:text-blue-600 hover:underline"
                          onClick={() => {
                            onKPIClick({
                              ...getFilterParams(),
                              department: payload.value,
                            });
                          }}
                        >
                          {payload.value}
                        </text>
                      </g>
                    );
                  }}
                />
                <YAxis stroke="#999" tick={{ fontSize: 11 }} />
                <Tooltip
                  contentStyle={{
                    backgroundColor: '#ffffff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '6px',
                    fontSize: '12px',
                  }}
                />
                <Legend
                  verticalAlign="bottom"
                  height={36}
                  iconType="square"
                  wrapperStyle={{ fontSize: '12px', paddingTop: '10px' }}
                />
                <Bar dataKey="approved" fill="#10b981" name="Approved" />
                <Bar dataKey="inProgress" fill="#f59e0b" name="Pending" />
                <Bar dataKey="rejected" fill="#ef4444" name="Rejected" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

