"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import {
  BarChart3,
  Phone,
  TrendingUp,
  Clock,
  Calendar,
  Loader2,
  SmilePlus,
  Meh,
  Frown,
  Target,
} from "lucide-react";

interface AnalyticsData {
  totalCalls: number;
  avgDurationSeconds: number;
  successRate: number;
  appointmentsBooked: number;
  sentimentBreakdown: { positive: number; neutral: number; negative: number };
  peakHours: Array<{ hour: number; callCount: number }>;
  dailyBreakdown: Array<{
    date: string;
    totalCalls: number;
    avgDuration: number;
    appointmentsBooked: number;
  }>;
  conversionFunnel: {
    totalCalls: number;
    answered: number;
    engaged: number;
    bookingAttempted: number;
    bookingCompleted: number;
  };
}

interface VoiceAnalyticsDashboardProps {
  lang: Lang;
}

type Period = "day" | "week" | "month";

function formatDuration(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}m ${secs}s`;
}

function ProgressBar({
  value,
  max,
  color,
}: {
  value: number;
  max: number;
  color: string;
}) {
  const pct = max > 0 ? Math.min(100, Math.round((value / max) * 100)) : 0;
  return (
    <div className="w-full h-2 rounded-full bg-slate-100">
      <div
        className={`h-2 rounded-full transition-all ${color}`}
        style={{ width: `${pct}%` }}
      />
    </div>
  );
}

export default function VoiceAnalyticsDashboard({
  lang,
}: VoiceAnalyticsDashboardProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState<Period>("week");
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);

  const fetchAnalytics = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/voice-agent/analytics?period=${period}`, {
        credentials: "include",
      });
      if (!res.ok) throw new Error("Failed to load");
      const data = await res.json();
      if (data.success) {
        setAnalytics(data.analytics);
      }
    } catch {
      // Keep existing state
    } finally {
      setLoading(false);
    }
  }, [period]);

  useEffect(() => {
    fetchAnalytics();
  }, [fetchAnalytics]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 animate-spin text-brand-green" />
        <span className="ml-3 text-slate-500">
          {isAr ? "جاري تحميل التحليلات..." : "Loading analytics..."}
        </span>
      </div>
    );
  }

  if (!analytics) {
    return (
      <div className="text-center py-20">
        <BarChart3 className="w-12 h-12 text-slate-200 mx-auto mb-3" />
        <p className="text-slate-400">
          {isAr ? "لا توجد بيانات متاحة" : "No analytics data available"}
        </p>
      </div>
    );
  }

  const totalSentiment =
    analytics.sentimentBreakdown.positive +
    analytics.sentimentBreakdown.neutral +
    analytics.sentimentBreakdown.negative;

  const funnel = analytics.conversionFunnel;

  return (
    <div className="space-y-6">
      {/* Period selector */}
      <div className="flex items-center justify-between">
        <h3 className="font-semibold text-slate-900">
          {isAr ? "التحليلات" : "Analytics"}
        </h3>
        <div className="flex items-center gap-1 bg-slate-50 rounded-xl p-1">
          {(["day", "week", "month"] as Period[]).map((p) => (
            <button
              key={p}
              onClick={() => setPeriod(p)}
              className={`px-4 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                period === p
                  ? "bg-white text-slate-800 shadow-sm"
                  : "text-slate-500 hover:text-slate-700"
              }`}
            >
              {p === "day"
                ? isAr
                  ? "اليوم"
                  : "Day"
                : p === "week"
                  ? isAr
                    ? "الأسبوع"
                    : "Week"
                  : isAr
                    ? "الشهر"
                    : "Month"}
            </button>
          ))}
        </div>
      </div>

      {/* Top-level stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
          <div className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center mb-3">
            <Phone className="w-4 h-4 text-blue-600" />
          </div>
          <p className="text-2xl font-bold text-slate-900">
            {analytics.totalCalls}
          </p>
          <p className="text-xs text-slate-500 mt-1">
            {isAr ? "إجمالي المكالمات" : "Total Calls"}
          </p>
        </div>
        <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
          <div className="w-9 h-9 rounded-lg bg-green-50 flex items-center justify-center mb-3">
            <TrendingUp className="w-4 h-4 text-green-600" />
          </div>
          <p className="text-2xl font-bold text-slate-900">
            {analytics.successRate}%
          </p>
          <p className="text-xs text-slate-500 mt-1">
            {isAr ? "نسبة النجاح" : "Success Rate"}
          </p>
        </div>
        <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
          <div className="w-9 h-9 rounded-lg bg-purple-50 flex items-center justify-center mb-3">
            <Calendar className="w-4 h-4 text-purple-600" />
          </div>
          <p className="text-2xl font-bold text-slate-900">
            {analytics.appointmentsBooked}
          </p>
          <p className="text-xs text-slate-500 mt-1">
            {isAr ? "مواعيد محجوزة" : "Booked"}
          </p>
        </div>
        <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
          <div className="w-9 h-9 rounded-lg bg-amber-50 flex items-center justify-center mb-3">
            <Clock className="w-4 h-4 text-amber-600" />
          </div>
          <p className="text-2xl font-bold text-slate-900">
            {formatDuration(analytics.avgDurationSeconds)}
          </p>
          <p className="text-xs text-slate-500 mt-1">
            {isAr ? "متوسط المدة" : "Avg Duration"}
          </p>
        </div>
      </div>

      {/* Sentiment + Funnel row */}
      <div className="grid lg:grid-cols-2 gap-6">
        {/* Sentiment Breakdown */}
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <h4 className="font-semibold text-slate-900 mb-4">
            {isAr ? "تحليل المشاعر" : "Sentiment Analysis"}
          </h4>
          {totalSentiment === 0 ? (
            <p className="text-sm text-slate-400 py-4">
              {isAr ? "لا توجد بيانات" : "No data yet"}
            </p>
          ) : (
            <div className="space-y-4">
              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <span className="flex items-center gap-2 text-sm text-slate-600">
                    <SmilePlus className="w-4 h-4 text-green-500" />
                    {isAr ? "إيجابي" : "Positive"}
                  </span>
                  <span className="text-sm font-medium text-slate-800">
                    {analytics.sentimentBreakdown.positive}
                    <span className="text-slate-400 text-xs ml-1">
                      (
                      {Math.round(
                        (analytics.sentimentBreakdown.positive /
                          totalSentiment) *
                          100,
                      )}
                      %)
                    </span>
                  </span>
                </div>
                <ProgressBar
                  value={analytics.sentimentBreakdown.positive}
                  max={totalSentiment}
                  color="bg-green-500"
                />
              </div>
              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <span className="flex items-center gap-2 text-sm text-slate-600">
                    <Meh className="w-4 h-4 text-slate-400" />
                    {isAr ? "محايد" : "Neutral"}
                  </span>
                  <span className="text-sm font-medium text-slate-800">
                    {analytics.sentimentBreakdown.neutral}
                    <span className="text-slate-400 text-xs ml-1">
                      (
                      {Math.round(
                        (analytics.sentimentBreakdown.neutral /
                          totalSentiment) *
                          100,
                      )}
                      %)
                    </span>
                  </span>
                </div>
                <ProgressBar
                  value={analytics.sentimentBreakdown.neutral}
                  max={totalSentiment}
                  color="bg-slate-300"
                />
              </div>
              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <span className="flex items-center gap-2 text-sm text-slate-600">
                    <Frown className="w-4 h-4 text-red-400" />
                    {isAr ? "سلبي" : "Negative"}
                  </span>
                  <span className="text-sm font-medium text-slate-800">
                    {analytics.sentimentBreakdown.negative}
                    <span className="text-slate-400 text-xs ml-1">
                      (
                      {Math.round(
                        (analytics.sentimentBreakdown.negative /
                          totalSentiment) *
                          100,
                      )}
                      %)
                    </span>
                  </span>
                </div>
                <ProgressBar
                  value={analytics.sentimentBreakdown.negative}
                  max={totalSentiment}
                  color="bg-red-400"
                />
              </div>
            </div>
          )}
        </div>

        {/* Conversion Funnel */}
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <div className="flex items-center gap-2 mb-4">
            <Target className="w-5 h-5 text-brand-green" />
            <h4 className="font-semibold text-slate-900">
              {isAr ? "قمع التحويل" : "Conversion Funnel"}
            </h4>
          </div>
          {funnel.totalCalls === 0 ? (
            <p className="text-sm text-slate-400 py-4">
              {isAr ? "لا توجد بيانات" : "No data yet"}
            </p>
          ) : (
            <div className="space-y-3">
              {[
                {
                  label: isAr ? "إجمالي المكالمات" : "Total Calls",
                  value: funnel.totalCalls,
                  color: "bg-blue-500",
                },
                {
                  label: isAr ? "تمت الإجابة" : "Answered",
                  value: funnel.answered,
                  color: "bg-cyan-500",
                },
                {
                  label: isAr ? "تفاعل (>30 ثانية)" : "Engaged (>30s)",
                  value: funnel.engaged,
                  color: "bg-brand-green",
                },
                {
                  label: isAr ? "محاولة حجز" : "Booking Attempted",
                  value: funnel.bookingAttempted,
                  color: "bg-purple-500",
                },
                {
                  label: isAr ? "حجز مكتمل" : "Booking Completed",
                  value: funnel.bookingCompleted,
                  color: "bg-emerald-500",
                },
              ].map((step, idx) => (
                <div key={idx}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm text-slate-600">{step.label}</span>
                    <span className="text-sm font-medium text-slate-800">
                      {step.value}
                    </span>
                  </div>
                  <ProgressBar
                    value={step.value}
                    max={funnel.totalCalls}
                    color={step.color}
                  />
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Daily breakdown */}
      {analytics.dailyBreakdown.length > 0 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <h4 className="font-semibold text-slate-900 mb-4">
            {isAr ? "التفاصيل اليومية" : "Daily Breakdown"}
          </h4>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100">
                  <th className="text-start text-xs font-medium text-slate-500 pb-3">
                    {isAr ? "التاريخ" : "Date"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 pb-3">
                    {isAr ? "المكالمات" : "Calls"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 pb-3">
                    {isAr ? "متوسط المدة" : "Avg Duration"}
                  </th>
                  <th className="text-start text-xs font-medium text-slate-500 pb-3">
                    {isAr ? "مواعيد" : "Booked"}
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {analytics.dailyBreakdown.map((day) => (
                  <tr key={day.date}>
                    <td className="py-2.5 text-sm text-slate-700">
                      {new Date(day.date).toLocaleDateString(
                        isAr ? "ar-QA" : "en-US",
                        { weekday: "short", month: "short", day: "numeric" },
                      )}
                    </td>
                    <td className="py-2.5 text-sm font-medium text-slate-800">
                      {day.totalCalls}
                    </td>
                    <td className="py-2.5 text-sm text-slate-600 font-mono">
                      {formatDuration(day.avgDuration)}
                    </td>
                    <td className="py-2.5">
                      {day.appointmentsBooked > 0 ? (
                        <span className="inline-flex px-2 py-0.5 rounded-full bg-brand-green/10 text-brand-green text-xs font-medium">
                          {day.appointmentsBooked}
                        </span>
                      ) : (
                        <span className="text-xs text-slate-300">0</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Peak Hours */}
      {analytics.peakHours.length > 0 && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
          <h4 className="font-semibold text-slate-900 mb-4">
            {isAr ? "ساعات الذروة" : "Peak Hours"}
          </h4>
          <div className="flex items-end gap-1 h-32">
            {Array.from({ length: 24 }, (_, hour) => {
              const data = analytics.peakHours.find((p) => p.hour === hour);
              const count = data?.callCount ?? 0;
              const maxCount = Math.max(
                ...analytics.peakHours.map((p) => p.callCount),
                1,
              );
              const heightPct = Math.max(4, (count / maxCount) * 100);
              return (
                <div
                  key={hour}
                  className="flex-1 flex flex-col items-center gap-1"
                  title={`${hour}:00 - ${count} ${isAr ? "مكالمات" : "calls"}`}
                >
                  <div
                    className={`w-full rounded-sm transition-all ${
                      count > 0 ? "bg-brand-green" : "bg-slate-100"
                    }`}
                    style={{ height: `${heightPct}%` }}
                  />
                  {hour % 4 === 0 && (
                    <span className="text-[9px] text-slate-400">{hour}</span>
                  )}
                </div>
              );
            })}
          </div>
          <p className="text-[10px] text-slate-400 mt-2 text-center">
            {isAr ? "عدد المكالمات حسب الساعة" : "Call volume by hour of day"}
          </p>
        </div>
      )}
    </div>
  );
}
