/**
 * Priority Distribution Report Component
 * Displays priority distribution analysis with pie chart
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Target } from 'lucide-react';
import { PriorityDistribution } from '@/services/dashboard.service';
import { formatHoursMinutes } from '@/utils/slaTracker';
import { ResponsiveContainer, PieChart as RechartsPieChart, Pie, Cell, Tooltip } from 'recharts';

interface PriorityDistributionReportProps {
  priorityDistribution: PriorityDistribution[];
  onNavigate?: (path: string) => void;
}

export function PriorityDistributionReport({
  priorityDistribution,
  onNavigate,
}: PriorityDistributionReportProps) {
  if (priorityDistribution.length === 0) return null;

  return (
    <Card className="shadow-md hover:shadow-lg transition-shadow" data-testid="priority-distribution-report">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <div className="bg-green-50 p-2 sm:p-3 rounded-lg">
            <Target className="h-5 w-5 sm:h-6 sm:w-6 text-green-600" />
          </div>
          <div>
            <CardTitle className="text-base sm:text-lg lg:text-xl">Priority Distribution Report</CardTitle>
            <CardDescription className="text-xs sm:text-sm">Express vs Standard workflow analysis</CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {/* Summary Cards */}
        <div className="grid grid-cols-2 gap-4 mb-6">
          {priorityDistribution.map((priority, idx) => {
            const avgCycleTime = Number(priority.avgCycleTimeHours) || 0;
            const isExpress = priority.priority === 'express';
            const bgColor = isExpress ? 'bg-red-50' : 'bg-blue-50';
            const dotColor = isExpress ? 'bg-red-500' : 'bg-blue-500';

            return (
              <div key={idx} className={`${bgColor} p-4 rounded-lg`} data-testid={`priority-card-${priority.priority}`}>
                <div className="flex items-center gap-2 mb-2">
                  <div className={`w-3 h-3 ${dotColor} rounded-full`}></div>
                  <span className="text-sm text-gray-600 capitalize">{priority.priority}</span>
                </div>
                <div className="text-2xl sm:text-3xl font-bold text-gray-900 mb-1">{priority.totalCount}</div>
                <div className="text-xs text-gray-500">Avg: {formatHoursMinutes(avgCycleTime)} cycle</div>
              </div>
            );
          })}
        </div>

        {/* Pie Chart */}
        <div className="flex justify-center">
          <ResponsiveContainer width="100%" height={300}>
            <RechartsPieChart>
              <Pie
                data={priorityDistribution.map((p) => ({
                  name: p.priority.charAt(0).toUpperCase() + p.priority.slice(1),
                  value: p.totalCount,
                  priority: p.priority,
                  percentage: Math.round(
                    (p.totalCount / priorityDistribution.reduce((sum, item) => sum + item.totalCount, 0)) * 100
                  ),
                }))}
                cx="50%"
                cy="50%"
                labelLine={true}
                label={({ cx, cy, midAngle, outerRadius, name, percentage }) => {
                  const RADIAN = Math.PI / 180;
                  const radius = outerRadius + 35;
                  const x = cx + radius * Math.cos(-midAngle * RADIAN);
                  const y = cy + radius * Math.sin(-midAngle * RADIAN);

                  return (
                    <text
                      x={x}
                      y={y}
                      fill="#1f2937"
                      textAnchor={x > cx ? 'start' : 'end'}
                      dominantBaseline="central"
                      className="text-sm font-semibold pointer-events-none"
                    >
                      {`${name}: ${percentage}%`}
                    </text>
                  );
                }}
                outerRadius={90}
                fill="#8884d8"
                dataKey="value"
                onClick={(data: any) => {
                  if (data && data.priority && onNavigate) {
                    onNavigate(`requests?priority=${data.priority}`);
                  }
                }}
                className="cursor-pointer"
              >
                {priorityDistribution.map((priority, index) => (
                  <Cell
                    key={`cell-${index}`}
                    fill={priority.priority === 'express' ? '#ef4444' : '#3b82f6'}
                    className="cursor-pointer"
                  />
                ))}
              </Pie>
              <Tooltip
                contentStyle={{
                  backgroundColor: '#ffffff',
                  border: '1px solid #e5e7eb',
                  borderRadius: '6px',
                  fontSize: '12px',
                }}
                formatter={(value: any, _name: any, props: any) => {
                  const priority = props.payload?.priority || '';
                  return [`${value} requests`, `Click for ${priority}`];
                }}
              />
            </RechartsPieChart>
          </ResponsiveContainer>
        </div>
      </CardContent>
    </Card>
  );
}

