"use client";

import { useState, useEffect, useCallback } from "react";
import {
  MessageSquare,
  AlertTriangle,
  RefreshCw,
  CheckCircle2,
  Clock,
  Bot,
  Send,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface WhatsAppHealthMetrics {
  conversationVolume: {
    sent: number;
    received: number;
    total: number;
    trend: number[];
  };
  deliverySuccess: {
    rate: number;
    sent: number;
    delivered: number;
    failed: number;
    failedReasons: Record<string, number>;
  };
  responseTime: {
    median: number;
    p95: number;
    target: number;
  };
  automation: {
    rate: number;
    automated: number;
    humanHandled: number;
  };
  templates: {
    approved: number;
    pending: number;
    blocked: number;
  };
  meta: {
    totalConversations: number;
    period: string;
    calculatedAt: string;
    workflowMetrics: {
      messagesReceived: number;
      messagesSent: number;
      appointmentsBooked: number;
    };
  };
}

// Format seconds to human readable
function formatTime(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  if (seconds < 3600) return `${Math.round(seconds / 60)}m`;
  return `${Math.round(seconds / 3600)}h`;
}

// Health indicator component
function HealthIndicator({
  value,
  thresholds,
  suffix = "%",
}: {
  value: number;
  thresholds: { good: number; warn: number };
  suffix?: string;
}) {
  const color =
    value >= thresholds.good
      ? "text-emerald-600"
      : value >= thresholds.warn
        ? "text-amber-600"
        : "text-red-600";

  return (
    <span className={`font-bold tabular-nums ${color}`}>
      {value.toFixed(1)}
      {suffix}
    </span>
  );
}

// Sparkline component
function Sparkline({
  data,
  color = "emerald",
}: {
  data: number[];
  color?: string;
}) {
  const max = Math.max(...data, 1);
  const colorClass = color === "emerald" ? "bg-emerald-500" : "bg-blue-500";

  return (
    <div className="flex items-end gap-0.5 h-8">
      {data.map((value, i) => (
        <div
          key={i}
          className={`w-2 ${colorClass} rounded-t opacity-70`}
          style={{ height: `${(value / max) * 100}%`, minHeight: "2px" }}
        />
      ))}
    </div>
  );
}

// Loading skeleton
function WhatsAppHealthSkeleton() {
  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="grid grid-cols-2 md:grid-cols-4 gap-6">
        {[...Array(4)].map((_, i) => (
          <div key={i}>
            <Skeleton className="h-4 w-20 mb-2" />
            <Skeleton className="h-8 w-24" />
          </div>
        ))}
      </div>
    </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 WhatsApp health
            </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 WhatsAppHealthCard() {
  const [data, setData] = useState<WhatsAppHealthMetrics | 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/whatsapp-health");
      if (!response.ok) {
        throw new Error("Failed to fetch WhatsApp health 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 <WhatsAppHealthSkeleton />;
  if (error) return <ErrorState message={error} onRetry={fetchData} />;
  if (!data) return null;

  const isDeliveryGood = data.deliverySuccess.rate >= 95;
  const isResponseGood = data.responseTime.median <= data.responseTime.target;
  const isAutomationGood = data.automation.rate >= 80;

  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-green-100 p-3">
            <MessageSquare className="h-6 w-6 text-green-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              WhatsApp Health
            </h3>
            <p className="text-xs text-gray-500">Last 30 days</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>

      {/* Main metrics */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-6">
        {/* Conversation Volume */}
        <div>
          <div className="flex items-center gap-2 mb-1">
            <Send className="h-4 w-4 text-gray-400" />
            <span className="text-xs font-medium text-gray-500">Messages</span>
          </div>
          <p className="text-xl font-bold tabular-nums text-gray-900">
            {data.conversationVolume.total.toLocaleString()}
          </p>
          <Sparkline data={data.conversationVolume.trend} />
        </div>

        {/* Delivery Success */}
        <div>
          <div className="flex items-center gap-2 mb-1">
            <CheckCircle2
              className={`h-4 w-4 ${isDeliveryGood ? "text-emerald-500" : "text-amber-500"}`}
            />
            <span className="text-xs font-medium text-gray-500">
              Delivery Rate
            </span>
          </div>
          <HealthIndicator
            value={data.deliverySuccess.rate}
            thresholds={{ good: 95, warn: 90 }}
          />
          <p className="text-xs text-gray-400 mt-1">
            {data.deliverySuccess.failed} failed
          </p>
        </div>

        {/* Response Time */}
        <div>
          <div className="flex items-center gap-2 mb-1">
            <Clock
              className={`h-4 w-4 ${isResponseGood ? "text-emerald-500" : "text-amber-500"}`}
            />
            <span className="text-xs font-medium text-gray-500">
              Response Time
            </span>
          </div>
          <p
            className={`text-xl font-bold tabular-nums ${isResponseGood ? "text-emerald-600" : "text-amber-600"}`}
          >
            {formatTime(data.responseTime.median)}
          </p>
          <p className="text-xs text-gray-400 mt-1">
            Target: {formatTime(data.responseTime.target)}
          </p>
        </div>

        {/* Automation Rate */}
        <div>
          <div className="flex items-center gap-2 mb-1">
            <Bot
              className={`h-4 w-4 ${isAutomationGood ? "text-emerald-500" : "text-amber-500"}`}
            />
            <span className="text-xs font-medium text-gray-500">
              Automation
            </span>
          </div>
          <HealthIndicator
            value={data.automation.rate}
            thresholds={{ good: 80, warn: 60 }}
          />
          <p className="text-xs text-gray-400 mt-1">
            {data.automation.humanHandled} human-handled
          </p>
        </div>
      </div>

      {/* Secondary metrics */}
      <div className="pt-4 border-t border-gray-100">
        <div className="grid grid-cols-3 gap-4 text-center">
          <div>
            <p className="text-sm font-semibold text-gray-900">
              {data.conversationVolume.sent.toLocaleString()}
            </p>
            <p className="text-xs text-gray-500">Sent</p>
          </div>
          <div>
            <p className="text-sm font-semibold text-gray-900">
              {data.conversationVolume.received.toLocaleString()}
            </p>
            <p className="text-xs text-gray-500">Received</p>
          </div>
          <div>
            <p className="text-sm font-semibold text-gray-900">
              {data.meta.totalConversations}
            </p>
            <p className="text-xs text-gray-500">Conversations</p>
          </div>
        </div>
      </div>

      {/* Status indicators */}
      <div className="mt-4 flex items-center gap-4 text-xs text-gray-500">
        <span className="flex items-center gap-1">
          <span
            className={`h-2 w-2 rounded-full ${isDeliveryGood ? "bg-emerald-500" : "bg-amber-500"}`}
          />
          Delivery: {isDeliveryGood ? "Healthy" : "Warning"}
        </span>
        <span className="flex items-center gap-1">
          <span
            className={`h-2 w-2 rounded-full ${isAutomationGood ? "bg-emerald-500" : "bg-amber-500"}`}
          />
          AI: {data.automation.automated} automated
        </span>
        <span className="ml-auto">
          Updated: {new Date(data.meta.calculatedAt).toLocaleTimeString()}
        </span>
      </div>
    </div>
  );
}
