import { BarChart3, ChevronDown } from 'lucide-react';

import { Link } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { CountUp } from '@/Components/ui/count-up';
import { EmptyState } from '@/Components/ui/empty-state';

interface FunnelMetrics {
  generated: number;
  approved: number;
  applied: number;
}

interface RecommendationFunnelProps {
  metrics: FunnelMetrics;
  siteId?: number;
}

interface FunnelStageProps {
  label: string;
  count: number;
  percentage: number;
  widthPercentage: number;
  conversionRate?: number | null;
  isLast?: boolean;
  href?: string;
  colorClass: string;
}

function FunnelStage({
  label,
  count,
  percentage,
  widthPercentage,
  conversionRate,
  isLast = false,
  href,
  colorClass,
}: FunnelStageProps) {
  const bar = (
    <div
      className={`relative ${colorClass} text-foreground rounded-lg py-4 px-6 transition-all duration-300 hover:opacity-90 ${href ? 'cursor-pointer' : ''}`}
      style={{ width: `${widthPercentage}%` }}
    >
      <div className="flex flex-col items-center justify-center gap-1">
        <div className="text-xs font-medium uppercase tracking-wide opacity-90">{label}</div>
        <div className="text-2xl font-bold">
          <CountUp end={count} />
        </div>
        <div className="text-xs opacity-75">{percentage.toFixed(1)}% of total</div>
      </div>
    </div>
  );

  return (
    <div className="flex flex-col items-center gap-2">
      {href ? (
        <Link href={href} className="flex justify-center w-full">
          {bar}
        </Link>
      ) : (
        bar
      )}

      {!isLast && (
        <div className="flex flex-col items-center gap-0.5 text-muted-foreground">
          <ChevronDown className="h-5 w-5" />
          {conversionRate !== null && conversionRate !== undefined && (
            <span className="text-xs font-medium">{conversionRate.toFixed(0)}% conversion</span>
          )}
        </div>
      )}
    </div>
  );
}

export default function RecommendationFunnel({ metrics, siteId }: RecommendationFunnelProps) {
  const { generated, approved, applied } = metrics;

  // Calculate percentages based on generated total
  const approvedPercentage = generated > 0 ? (approved / generated) * 100 : 0;
  const appliedPercentage = generated > 0 ? (applied / generated) * 100 : 0;

  // Stage-to-stage conversion rates
  const generatedToApprovedRate = generated > 0 ? (approved / generated) * 100 : 0;
  const approvedToAppliedRate = approved > 0 ? (applied / approved) * 100 : 0;

  // Calculate funnel bar widths (visual representation)
  const maxWidth = 100;
  const approvedWidth = generated > 0 ? Math.max(30, (approved / generated) * maxWidth) : 30;
  const appliedWidth = generated > 0 ? Math.max(20, (applied / generated) * maxWidth) : 20;

  const generatedHref = siteId ? route('recommendations.index', siteId) : undefined;
  const approvedHref = siteId
    ? route('recommendations.index', siteId) + '?lifecycle_status=approved'
    : undefined;
  const appliedHref = siteId
    ? route('recommendations.index', siteId) + '?lifecycle_status=applied'
    : undefined;

  return (
    <Card>
      <CardHeader>
        <CardTitle>Recommendation Funnel</CardTitle>
        <CardDescription>
          Track recommendations from generation to implementation
          {siteId ? ' — click a stage to filter' : ''}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {generated === 0 ? (
          <EmptyState
            icon={BarChart3}
            title="No recommendations yet"
            description="Run an analysis first to generate recommendations."
            size="sm"
            animated={false}
            action={
              siteId ? (
                <Button size="sm" variant="outline" asChild>
                  <Link href={route('analyze.index', siteId)}>Run Analysis</Link>
                </Button>
              ) : undefined
            }
          />
        ) : (
          <div className="flex flex-col items-center gap-4 py-4">
            <FunnelStage
              label="Generated"
              count={generated}
              percentage={100}
              widthPercentage={maxWidth}
              conversionRate={generatedToApprovedRate}
              colorClass="bg-primary"
              href={generatedHref}
            />

            <FunnelStage
              label="Approved"
              count={approved}
              percentage={approvedPercentage}
              widthPercentage={approvedWidth}
              conversionRate={approvedToAppliedRate}
              colorClass="bg-success"
              href={approvedHref}
            />

            <FunnelStage
              label="Applied"
              count={applied}
              percentage={appliedPercentage}
              widthPercentage={appliedWidth}
              isLast
              colorClass="bg-warning"
              href={appliedHref}
            />
          </div>
        )}
      </CardContent>
    </Card>
  );
}
