/**
 * Analytics Dashboard Component - Task 7
 * Displays daily/weekly/monthly metrics with period selector
 */

"use client";

import { useState, useEffect } from "react";

interface AnalyticsDashboardProps {
  userId: string;
  packageTier: string;
  lang: string;
}

interface AnalyticsData {
  totalConversations: number;
  messagesReceived: number;
  messagesSent: number;
  activeCustomers: number;
  platformBreakdown: {
    whatsapp: number;
    voice: number;
    social: number;
  };
  topCustomers: Array<{
    name: string;
    phone: string;
    messageCount: number;
  }>;
}

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

export default function AnalyticsDashboard({
  userId,
  packageTier,
  lang,
}: AnalyticsDashboardProps) {
  const isAr = lang === "ar";
  const [period, setPeriod] = useState<Period>("today");
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Fetch analytics data
  useEffect(() => {
    let mounted = true;

    async function fetchAnalytics() {
      setLoading(true);
      setError(null);

      try {
        // Calculate date based on period
        const now = new Date();
        let dateParam = now.toISOString().split("T")[0]; // Today

        if (period === "week") {
          const weekAgo = new Date(now);
          weekAgo.setDate(weekAgo.getDate() - 7);
          dateParam = weekAgo.toISOString().split("T")[0];
        } else if (period === "month") {
          const monthAgo = new Date(now);
          monthAgo.setMonth(monthAgo.getMonth() - 1);
          dateParam = monthAgo.toISOString().split("T")[0];
        }

        const response = await fetch(
          `/api/dashboard/analytics/daily?date=${dateParam}&period=${period}`,
        );

        if (!response.ok) {
          throw new Error("Failed to load analytics");
        }

        const result = await response.json();

        if (mounted) {
          // The API returns { success: true, stats: {...}, date: '...' }
          // Extract the stats object, or use result directly if it has the expected shape
          const analyticsData = result.stats || result;

          // Ensure required fields exist with defaults
          setData({
            totalConversations: analyticsData.totalConversations || 0,
            messagesReceived: analyticsData.messagesReceived || 0,
            messagesSent: analyticsData.messagesSent || 0,
            activeCustomers: analyticsData.activeCustomers || 0,
            platformBreakdown: analyticsData.platformBreakdown || {
              whatsapp: 0,
              voice: 0,
              social: 0,
            },
            topCustomers: analyticsData.topCustomers || [],
          });
        }
      } catch (err) {
        console.error("Analytics fetch error:", err);
        if (mounted) {
          setError(
            err instanceof Error ? err.message : "Failed to load analytics",
          );
          // Set mock data for development
          setData({
            totalConversations: 0,
            messagesReceived: 0,
            messagesSent: 0,
            activeCustomers: 0,
            platformBreakdown: {
              whatsapp: 0,
              voice: 0,
              social: 0,
            },
            topCustomers: [],
          });
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    }

    fetchAnalytics();

    return () => {
      mounted = false;
    };
  }, [period]);

  if (loading) {
    return <AnalyticsLoadingSkeleton />;
  }

  // Translations
  const t = {
    title: isAr ? "لوحة التحليلات" : "Analytics Dashboard",
    today: isAr ? "اليوم" : "Today",
    week: isAr ? "هذا الأسبوع" : "This Week",
    month: isAr ? "هذا الشهر" : "This Month",
    totalConversations: isAr ? "إجمالي المحادثات" : "Total Conversations",
    messagesReceived: isAr ? "الرسائل الواردة" : "Messages Received",
    messagesSent: isAr ? "الرسائل المرسلة" : "Messages Sent",
    activeCustomers: isAr ? "العملاء النشطون" : "Active Customers",
    platformBreakdown: isAr ? "التوزيع حسب المنصة" : "Platform Breakdown",
    topCustomers: isAr ? "أفضل العملاء" : "Top Customers",
    whatsapp: isAr ? "واتساب" : "WhatsApp",
    voice: isAr ? "مكالمات صوتية" : "Voice Calls",
    social: isAr ? "وسائل التواصل" : "Social Media",
    messages: isAr ? "رسالة" : "messages",
    noData: isAr ? "لا توجد بيانات بعد" : "No data yet",
    noDataDesc: isAr
      ? "ستظهر البيانات عند بدء التفاعل مع العملاء"
      : "Data will appear when you start interacting with customers",
  };

  if (!data) {
    return (
      <div className="rounded-xl bg-amber-50 border-2 border-amber-200 p-8 text-center">
        <div className="text-5xl mb-3">📊</div>
        <h3 className="text-lg font-semibold text-slate-900 mb-2">
          {t.noData}
        </h3>
        <p className="text-sm text-slate-600">{t.noDataDesc}</p>
      </div>
    );
  }

  // Calculate platform totals with safe defaults
  const platformBreakdown = data.platformBreakdown || {
    whatsapp: 0,
    voice: 0,
    social: 0,
  };
  const platformTotal =
    (platformBreakdown.whatsapp || 0) +
    (platformBreakdown.voice || 0) +
    (platformBreakdown.social || 0);

  return (
    <div className="space-y-6">
      {/* Header with Period Selector */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-sm text-slate-600 mt-1">
            {period === "today" && t.today}
            {period === "week" && t.week}
            {period === "month" && t.month}
          </p>
        </div>

        {/* Period Tabs */}
        <div className="flex gap-2 rounded-lg bg-slate-100 p-1">
          {(["today", "week", "month"] as Period[]).map((p) => (
            <button
              key={p}
              onClick={() => setPeriod(p)}
              className={`rounded-md px-4 py-2 text-sm font-medium transition-all ${
                period === p
                  ? "bg-white text-brand-green shadow-sm"
                  : "text-slate-600 hover:text-slate-900"
              }`}
            >
              {p === "today" && t.today}
              {p === "week" && t.week}
              {p === "month" && t.month}
            </button>
          ))}
        </div>
      </div>

      {/* Error Display */}
      {error && (
        <div className="rounded-lg bg-amber-50 border border-amber-200 p-4">
          <p className="text-sm text-amber-800">⚠️ {error}</p>
        </div>
      )}

      {/* Metric Cards Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {/* Total Conversations */}
        <MetricCard
          title={t.totalConversations}
          value={data.totalConversations}
          icon="💬"
          color="blue"
          iconBg="bg-blue-100"
          iconColor="text-blue-600"
        />

        {/* Messages Received */}
        <MetricCard
          title={t.messagesReceived}
          value={data.messagesReceived}
          icon="📥"
          color="green"
          iconBg="bg-green-100"
          iconColor="text-green-600"
        />

        {/* Messages Sent */}
        <MetricCard
          title={t.messagesSent}
          value={data.messagesSent}
          icon="📤"
          color="purple"
          iconBg="bg-purple-100"
          iconColor="text-purple-600"
        />

        {/* Active Customers */}
        <MetricCard
          title={t.activeCustomers}
          value={data.activeCustomers}
          icon="👥"
          color="orange"
          iconBg="bg-orange-100"
          iconColor="text-orange-600"
        />
      </div>

      {/* Platform Breakdown */}
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <h3 className="text-base font-semibold text-slate-900 mb-4">
          {t.platformBreakdown}
        </h3>
        <div className="space-y-4">
          {/* WhatsApp */}
          <PlatformBar
            label={t.whatsapp}
            count={platformBreakdown.whatsapp}
            total={platformTotal}
            color="bg-green-500"
            icon="📱"
          />

          {/* Voice */}
          <PlatformBar
            label={t.voice}
            count={platformBreakdown.voice}
            total={platformTotal}
            color="bg-blue-500"
            icon="📞"
          />

          {/* Social */}
          <PlatformBar
            label={t.social}
            count={platformBreakdown.social}
            total={platformTotal}
            color="bg-purple-500"
            icon="💬"
          />
        </div>
      </div>

      {/* Top Customers */}
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <h3 className="text-base font-semibold text-slate-900 mb-4">
          {t.topCustomers}
        </h3>
        {!data.topCustomers || data.topCustomers.length === 0 ? (
          <p className="text-sm text-slate-500 text-center py-4">
            {isAr ? "لا يوجد عملاء بعد" : "No customers yet"}
          </p>
        ) : (
          <div className="space-y-3">
            {data.topCustomers.slice(0, 5).map((customer, index) => (
              <div
                key={customer.phone}
                className="flex items-center justify-between p-3 rounded-lg bg-slate-50 hover:bg-slate-100 transition-colors"
              >
                <div className="flex items-center gap-3">
                  <span className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-green/10 text-xs font-bold text-brand-green">
                    {index + 1}
                  </span>
                  <div>
                    <p className="text-sm font-medium text-slate-900">
                      {customer.name || customer.phone}
                    </p>
                    {customer.name && (
                      <p className="text-xs text-slate-500">{customer.phone}</p>
                    )}
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-sm font-semibold text-slate-900">
                    {customer.messageCount}
                  </p>
                  <p className="text-xs text-slate-500">{t.messages}</p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// Metric Card Component
function MetricCard({
  title,
  value,
  icon,
  color,
  iconBg,
  iconColor,
}: {
  title: string;
  value: number;
  icon: string;
  color: string;
  iconBg: string;
  iconColor: string;
}) {
  // Static color variants mapping for Tailwind JIT compiler
  const colorVariants: Record<string, string> = {
    blue: "bg-blue-500",
    green: "bg-green-500",
    purple: "bg-purple-500",
    orange: "bg-orange-500",
    red: "bg-red-500",
    yellow: "bg-yellow-500",
    pink: "bg-pink-500",
    teal: "bg-teal-500",
    emerald: "bg-emerald-500",
  };

  return (
    <div className="group relative overflow-hidden rounded-xl bg-white p-5 shadow-sm border border-slate-200 transition-all hover:shadow-md">
      {/* Icon */}
      <div
        className={`flex h-12 w-12 items-center justify-center rounded-lg ${iconBg} mb-3`}
      >
        <span className={`text-2xl ${iconColor}`}>{icon}</span>
      </div>

      {/* Content */}
      <div>
        <p className="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">
          {title}
        </p>
        <p className="text-3xl font-bold text-slate-900">
          {value.toLocaleString()}
        </p>
      </div>

      {/* Bottom accent line */}
      <div
        className={`absolute bottom-0 left-0 right-0 h-1 ${colorVariants[color] || colorVariants.blue}`}
      ></div>
    </div>
  );
}

// Platform Bar Component
function PlatformBar({
  label,
  count,
  total,
  color,
  icon,
}: {
  label: string;
  count: number;
  total: number;
  color: string;
  icon: string;
}) {
  const percentage = total > 0 ? Math.round((count / total) * 100) : 0;

  return (
    <div>
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2">
          <span className="text-lg">{icon}</span>
          <span className="text-sm font-medium text-slate-700">{label}</span>
        </div>
        <span className="text-sm font-semibold text-slate-900">
          {count} ({percentage}%)
        </span>
      </div>
      <div className="h-3 w-full rounded-full bg-slate-100 overflow-hidden">
        <div
          className={`h-full ${color} transition-all duration-500`}
          style={{ width: `${percentage}%` }}
        ></div>
      </div>
    </div>
  );
}

// Loading Skeleton Component
export function AnalyticsLoadingSkeleton() {
  return (
    <div className="space-y-6 animate-pulse">
      {/* Header Skeleton */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <div className="h-7 w-48 bg-slate-200 rounded"></div>
          <div className="h-4 w-32 bg-slate-200 rounded mt-2"></div>
        </div>
        <div className="h-12 w-80 bg-slate-200 rounded-lg"></div>
      </div>

      {/* Metric Cards Skeleton */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[1, 2, 3, 4].map((i) => (
          <div
            key={i}
            className="rounded-xl bg-white p-5 shadow-sm border border-slate-200"
          >
            <div className="h-12 w-12 bg-slate-200 rounded-lg mb-3"></div>
            <div className="h-3 w-24 bg-slate-200 rounded mb-2"></div>
            <div className="h-8 w-20 bg-slate-200 rounded"></div>
          </div>
        ))}
      </div>

      {/* Platform Breakdown Skeleton */}
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <div className="h-6 w-40 bg-slate-200 rounded mb-4"></div>
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i}>
              <div className="flex justify-between mb-2">
                <div className="h-4 w-24 bg-slate-200 rounded"></div>
                <div className="h-4 w-16 bg-slate-200 rounded"></div>
              </div>
              <div className="h-3 w-full bg-slate-200 rounded-full"></div>
            </div>
          ))}
        </div>
      </div>

      {/* Top Customers Skeleton */}
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <div className="h-6 w-32 bg-slate-200 rounded mb-4"></div>
        <div className="space-y-3">
          {[1, 2, 3, 4, 5].map((i) => (
            <div
              key={i}
              className="flex items-center justify-between p-3 rounded-lg bg-slate-50"
            >
              <div className="flex items-center gap-3">
                <div className="h-8 w-8 bg-slate-200 rounded-full"></div>
                <div>
                  <div className="h-4 w-32 bg-slate-200 rounded mb-1"></div>
                  <div className="h-3 w-24 bg-slate-200 rounded"></div>
                </div>
              </div>
              <div>
                <div className="h-4 w-12 bg-slate-200 rounded mb-1"></div>
                <div className="h-3 w-16 bg-slate-200 rounded"></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
