"use client";

import { useState, useEffect } from "react";
import {
  ArrowRight,
  TrendingUp,
  TrendingDown,
  Clock,
  Target,
  AlertCircle,
} from "lucide-react";

// Pipeline data types
interface PipelineData {
  period: string;
  stages: {
    visitors: number;
    demos: number;
    qualified: number;
    proposals: number;
    won: number;
    lost: number;
  };
  conversions: {
    visitorToDemo: number;
    demoToQualified: number;
    qualifiedToProposal: number;
    proposalToWon: number;
    overallConversion: number;
  };
  winVelocity: {
    avgDays: number;
    medianDays: number;
  };
  comparison: {
    visitorsChange: number;
    demosChange: number;
    wonChange: number;
  };
}

// Stage configuration
const STAGES = [
  {
    key: "visitors",
    name: "Visitors",
    color: "bg-blue-500",
    hoverColor: "hover:bg-blue-600",
  },
  {
    key: "demos",
    name: "Demos",
    color: "bg-indigo-500",
    hoverColor: "hover:bg-indigo-600",
  },
  {
    key: "qualified",
    name: "Qualified",
    color: "bg-purple-500",
    hoverColor: "hover:bg-purple-600",
  },
  {
    key: "proposals",
    name: "Proposals",
    color: "bg-pink-500",
    hoverColor: "hover:bg-pink-600",
  },
  {
    key: "won",
    name: "Won",
    color: "bg-green-500",
    hoverColor: "hover:bg-green-600",
  },
] as const;

// Change indicator component
function ChangeIndicator({
  change,
  label,
}: {
  change: number;
  label?: string;
}) {
  const isPositive = change >= 0;
  const Icon = isPositive ? TrendingUp : TrendingDown;
  const colorClass = isPositive ? "text-green-600" : "text-red-600";

  return (
    <div className={`flex items-center gap-1 text-xs ${colorClass}`}>
      <Icon className="h-3 w-3" />
      <span>
        {isPositive ? "+" : ""}
        {change.toFixed(1)}%
      </span>
      {label && <span className="text-gray-500">{label}</span>}
    </div>
  );
}

// Conversion arrow component
function ConversionArrow({ rate }: { rate: number }) {
  return (
    <div className="flex flex-col items-center justify-center px-1">
      <ArrowRight className="h-4 w-4 text-gray-400" />
      <span className="text-xs text-gray-500 font-medium">
        {rate.toFixed(1)}%
      </span>
    </div>
  );
}

// Loading skeleton
function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-4">
      <div className="h-48 bg-gray-200 rounded" />
      <div className="grid grid-cols-3 gap-4">
        <div className="h-16 bg-gray-200 rounded" />
        <div className="h-16 bg-gray-200 rounded" />
        <div className="h-16 bg-gray-200 rounded" />
      </div>
    </div>
  );
}

export function PipelineFunnel() {
  const [data, setData] = useState<PipelineData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [period, setPeriod] = useState("30d");

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(
          `/api/staff/analytics/pipeline?period=${period}`,
          {
            credentials: "include",
          },
        );

        if (!response.ok) {
          throw new Error("Failed to fetch pipeline data");
        }

        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err instanceof Error ? err.message : "An error occurred");
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [period]);

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          Sales Pipeline
        </h3>
        <LoadingSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          Sales Pipeline
        </h3>
        <div className="text-center py-8 text-gray-500">
          <AlertCircle className="h-8 w-8 mx-auto mb-2 text-red-500" />
          <p>Failed to load pipeline data</p>
          <p className="text-sm">{error}</p>
        </div>
      </div>
    );
  }

  if (!data) return null;

  // Calculate max for bar heights
  const maxValue = Math.max(
    data.stages.visitors,
    data.stages.demos,
    data.stages.qualified,
    data.stages.proposals,
    data.stages.won,
  );

  // Get conversion rates
  const conversionRates = [
    data.conversions.visitorToDemo,
    data.conversions.demoToQualified,
    data.conversions.qualifiedToProposal,
    data.conversions.proposalToWon,
  ];

  return (
    <div className="bg-white rounded-lg shadow p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-semibold text-gray-900">Sales Pipeline</h3>
        <select
          value={period}
          onChange={(e) => setPeriod(e.target.value)}
          className="px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="7d">Last 7 days</option>
          <option value="30d">Last 30 days</option>
          <option value="90d">Last 90 days</option>
        </select>
      </div>

      {/* Funnel Visualization */}
      <div className="flex items-end justify-between gap-1 h-48 mb-6">
        {STAGES.map((stage, index) => {
          const value = data.stages[stage.key as keyof typeof data.stages];
          const height = maxValue > 0 ? (value / maxValue) * 100 : 0;

          return (
            <div key={stage.key} className="flex items-end flex-1">
              {/* Bar */}
              <div className="flex flex-col items-center flex-1">
                <button
                  className={`w-full ${stage.color} ${stage.hoverColor} rounded-t transition-all cursor-pointer`}
                  style={{
                    height: `${Math.max(height, 5)}%`,
                    minHeight: "12px",
                  }}
                  onClick={() => {
                    window.location.href = `/staff/dashboard?filter=${stage.key}`;
                  }}
                >
                  <span className="sr-only">View {stage.name}</span>
                </button>
                <span className="text-xs mt-2 font-medium text-gray-500">
                  {stage.name}
                </span>
                <span className="text-lg font-bold text-gray-900">
                  {value.toLocaleString()}
                </span>
              </div>

              {/* Conversion Arrow (not after last stage) */}
              {index < STAGES.length - 1 && (
                <ConversionArrow rate={conversionRates[index]} />
              )}
            </div>
          );
        })}
      </div>

      {/* Metrics Grid */}
      <div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-200">
        {/* Overall Conversion */}
        <div className="text-center">
          <div className="flex items-center justify-center gap-1 text-gray-500 mb-1">
            <Target className="h-4 w-4" />
            <span className="text-xs">Overall Conversion</span>
          </div>
          <div className="text-2xl font-bold text-green-600">
            {data.conversions.overallConversion.toFixed(2)}%
          </div>
        </div>

        {/* Win Velocity */}
        <div className="text-center">
          <div className="flex items-center justify-center gap-1 text-gray-500 mb-1">
            <Clock className="h-4 w-4" />
            <span className="text-xs">Win Velocity</span>
          </div>
          <div className="text-2xl font-bold text-gray-900">
            {data.winVelocity.avgDays.toFixed(1)}
            <span className="text-sm font-normal text-gray-500 ml-1">days</span>
          </div>
        </div>

        {/* Period Comparison */}
        <div className="text-center">
          <div className="text-xs text-gray-500 mb-1">vs Previous Period</div>
          <div className="space-y-1">
            <ChangeIndicator
              change={data.comparison.visitorsChange}
              label="visitors"
            />
            <ChangeIndicator
              change={data.comparison.demosChange}
              label="demos"
            />
            <ChangeIndicator change={data.comparison.wonChange} label="won" />
          </div>
        </div>
      </div>
    </div>
  );
}

export default PipelineFunnel;
