"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Rocket,
  AlertTriangle,
  RefreshCw,
  CheckCircle2,
  Calendar,
  Workflow,
  BookOpen,
  TrendingUp,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface FeatureAdoptionMetrics {
  onboarding: {
    step1_profile: number;
    step2_knowledge: number;
    step3_whatsapp: number;
    step4_workflow: number;
    step5_testing: number;
    fullyComplete: number;
  };
  usage: {
    bookingsPerClinicPerWeek: number;
    activeWorkflows: number;
    knowledgeBaseQueries: number;
    clinicsWithBookings: number;
    totalWeeklyBookings: number;
  };
  cohorts: {
    week1Retention: number;
    week2Retention: number;
    week4Retention: number;
    week8Retention: number;
  };
  meta: {
    totalUsers: number;
    totalOnboardingRecords: number;
    workflowActivationRate: number;
    calculatedAt: string;
    cohortSizes: {
      week1: number;
      week2: number;
      week4: number;
      week8: number;
    };
  };
}

// Progress bar for funnel
function FunnelStep({
  label,
  value,
  color,
}: {
  label: string;
  value: number;
  color: string;
}) {
  return (
    <div className="flex items-center gap-3">
      <div className="w-24 text-xs text-gray-600 truncate">{label}</div>
      <div className="flex-1 h-4 bg-gray-100 rounded-full overflow-hidden">
        <div
          className={`h-full ${color} transition-all duration-500`}
          style={{ width: `${Math.min(value, 100)}%` }}
        />
      </div>
      <div className="w-12 text-xs font-semibold text-gray-900 text-right tabular-nums">
        {value.toFixed(0)}%
      </div>
    </div>
  );
}

// Retention cohort badge
function CohortBadge({
  label,
  retention,
  size,
}: {
  label: string;
  retention: number;
  size: number;
}) {
  const color =
    retention >= 60
      ? "bg-emerald-50 text-emerald-700 border-emerald-200"
      : retention >= 40
        ? "bg-amber-50 text-amber-700 border-amber-200"
        : "bg-red-50 text-red-700 border-red-200";

  return (
    <div className={`rounded-lg border p-2 text-center ${color}`}>
      <p className="text-xs font-medium">{label}</p>
      <p className="text-lg font-bold tabular-nums">{retention.toFixed(0)}%</p>
      <p className="text-[10px] opacity-70">n={size}</p>
    </div>
  );
}

// Loading skeleton
function FeatureAdoptionSkeleton() {
  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6">
      <div className="flex items-center justify-between mb-6">
        <Skeleton className="h-6 w-48" />
        <Skeleton className="h-8 w-8 rounded-full" />
      </div>
      <div className="space-y-3 mb-4">
        {[...Array(5)].map((_, i) => (
          <Skeleton key={i} className="h-4 w-full" />
        ))}
      </div>
      <Skeleton className="h-20" />
    </div>
  );
}

// Error state component
function ErrorState({
  message,
  onRetry,
}: {
  message: string;
  onRetry: () => void;
}) {
  return (
    <div className="rounded-2xl border border-red-100 bg-red-50 p-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-red-100 p-2">
            <AlertTriangle className="h-5 w-5 text-red-600" />
          </div>
          <div>
            <p className="font-medium text-red-900">
              Failed to load adoption data
            </p>
            <p className="text-sm text-red-700">{message}</p>
          </div>
        </div>
        <button
          onClick={onRetry}
          className="flex items-center gap-2 rounded-lg bg-red-100 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-200 transition-colors"
        >
          <RefreshCw className="h-4 w-4" />
          Retry
        </button>
      </div>
    </div>
  );
}

export default function FeatureAdoptionCard() {
  const [data, setData] = useState<FeatureAdoptionMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/staff/analytics/feature-adoption");
      if (!response.ok) {
        throw new Error("Failed to fetch feature adoption data");
      }
      const result = await response.json();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [fetchData]);

  if (loading) return <FeatureAdoptionSkeleton />;
  if (error) return <ErrorState message={error} onRetry={fetchData} />;
  if (!data) return null;

  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm hover:shadow-lg transition-shadow">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="rounded-xl bg-purple-100 p-3">
            <Rocket className="h-6 w-6 text-purple-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Feature Adoption
            </h3>
            <p className="text-xs text-gray-500">Onboarding & usage metrics</p>
          </div>
        </div>
        <button
          onClick={fetchData}
          disabled={loading}
          className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors disabled:opacity-50"
          title="Refresh data"
        >
          <RefreshCw className={`h-5 w-5 ${loading ? "animate-spin" : ""}`} />
        </button>
      </div>

      {/* Onboarding funnel */}
      <div className="mb-6">
        <div className="flex items-center gap-2 mb-3">
          <CheckCircle2 className="h-4 w-4 text-purple-500" />
          <span className="text-sm font-medium text-gray-700">
            Onboarding Funnel
          </span>
        </div>
        <div className="space-y-2">
          <FunnelStep
            label="Welcome"
            value={data.onboarding.step1_profile}
            color="bg-purple-500"
          />
          <FunnelStep
            label="Knowledge"
            value={data.onboarding.step2_knowledge}
            color="bg-purple-400"
          />
          <FunnelStep
            label="WhatsApp"
            value={data.onboarding.step3_whatsapp}
            color="bg-purple-300"
          />
          <FunnelStep
            label="Workflows"
            value={data.onboarding.step4_workflow}
            color="bg-purple-200"
          />
          <FunnelStep
            label="Testing"
            value={data.onboarding.step5_testing}
            color="bg-purple-100"
          />
        </div>
        <div className="mt-3 flex items-center justify-between text-xs">
          <span className="text-gray-500">Fully complete</span>
          <span className="font-semibold text-purple-600">
            {data.onboarding.fullyComplete.toFixed(0)}%
          </span>
        </div>
      </div>

      {/* Usage metrics */}
      <div className="border-t border-gray-100 pt-4 mb-4">
        <div className="flex items-center gap-2 mb-3">
          <TrendingUp className="h-4 w-4 text-emerald-500" />
          <span className="text-sm font-medium text-gray-700">
            Weekly Usage
          </span>
        </div>
        <div className="grid grid-cols-3 gap-4 text-center">
          <div>
            <div className="flex items-center justify-center gap-1">
              <Calendar className="h-4 w-4 text-blue-500" />
              <span className="text-lg font-bold text-gray-900 tabular-nums">
                {data.usage.totalWeeklyBookings}
              </span>
            </div>
            <p className="text-xs text-gray-500">Bookings</p>
            <p className="text-[10px] text-gray-400">
              {data.usage.bookingsPerClinicPerWeek.toFixed(1)}/clinic
            </p>
          </div>
          <div>
            <div className="flex items-center justify-center gap-1">
              <Workflow className="h-4 w-4 text-green-500" />
              <span className="text-lg font-bold text-gray-900 tabular-nums">
                {data.usage.activeWorkflows}
              </span>
            </div>
            <p className="text-xs text-gray-500">Workflows</p>
            <p className="text-[10px] text-gray-400">
              {data.meta.workflowActivationRate.toFixed(0)}% active
            </p>
          </div>
          <div>
            <div className="flex items-center justify-center gap-1">
              <BookOpen className="h-4 w-4 text-amber-500" />
              <span className="text-lg font-bold text-gray-900 tabular-nums">
                {data.usage.knowledgeBaseQueries}
              </span>
            </div>
            <p className="text-xs text-gray-500">KB Setup</p>
          </div>
        </div>
      </div>

      {/* Retention cohorts */}
      <div className="border-t border-gray-100 pt-4">
        <div className="flex items-center gap-2 mb-3">
          <TrendingUp className="h-4 w-4 text-blue-500" />
          <span className="text-sm font-medium text-gray-700">
            Retention by Cohort
          </span>
        </div>
        <div className="grid grid-cols-4 gap-2">
          <CohortBadge
            label="Week 1"
            retention={data.cohorts.week1Retention}
            size={data.meta.cohortSizes.week1}
          />
          <CohortBadge
            label="Week 2"
            retention={data.cohorts.week2Retention}
            size={data.meta.cohortSizes.week2}
          />
          <CohortBadge
            label="Week 4"
            retention={data.cohorts.week4Retention}
            size={data.meta.cohortSizes.week4}
          />
          <CohortBadge
            label="Week 8+"
            retention={data.cohorts.week8Retention}
            size={data.meta.cohortSizes.week8}
          />
        </div>
      </div>

      {/* Footer */}
      <div className="mt-4 flex items-center justify-between text-xs text-gray-500">
        <span>{data.meta.totalUsers} total users</span>
        <span>
          Updated: {new Date(data.meta.calculatedAt).toLocaleTimeString()}
        </span>
      </div>
    </div>
  );
}
