"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";

interface AnalyticsDashboardProps {
  lang: Lang;
}

export default function AnalyticsDashboard({ lang }: AnalyticsDashboardProps) {
  const [animatedStats, setAnimatedStats] = useState({
    sent: 0,
    delivered: 0,
    read: 0,
    replied: 0,
  });

  const isRTL = lang === "ar";

  const content = {
    ar: {
      title: "لوحة تحليلات الرسائل",
      subtitle: "نظرة شاملة على أداء رسائلك",
      stats: {
        sent: { label: "رسائل مرسلة", value: 15234, icon: "📤", color: "blue" },
        delivered: {
          label: "تم التسليم",
          value: 14987,
          icon: "✅",
          color: "green",
        },
        read: {
          label: "تم القراءة",
          value: 13456,
          icon: "👁",
          color: "purple",
        },
        replied: { label: "تم الرد", value: 9876, icon: "💬", color: "orange" },
      },
      charts: {
        title: "أداء الرسائل خلال 7 أيام",
        labels: [
          "السبت",
          "الأحد",
          "الاثنين",
          "الثلاثاء",
          "الأربعاء",
          "الخميس",
          "الجمعة",
        ],
      },
      topTemplates: {
        title: "أكثر القوالب استخداماً",
        data: [
          { name: "تذكير موعد - 24 ساعة", sent: 3456, rate: 95 },
          { name: "تأكيد حجز", sent: 2987, rate: 98 },
          { name: "متابعة ما بعد الزيارة", sent: 1876, rate: 87 },
          { name: "عرض خاص شهري", sent: 1234, rate: 72 },
        ],
      },
      deliveryRate: "معدل التسليم",
      readRate: "معدل القراءة",
      responseRate: "معدل الاستجابة",
      avgResponseTime: "متوسط وقت الرد",
      minutes: "دقيقة",
    },
    en: {
      title: "Message Analytics Dashboard",
      subtitle: "Comprehensive overview of your messaging performance",
      stats: {
        sent: {
          label: "Messages Sent",
          value: 15234,
          icon: "📤",
          color: "blue",
        },
        delivered: {
          label: "Delivered",
          value: 14987,
          icon: "✅",
          color: "green",
        },
        read: { label: "Read", value: 13456, icon: "👁", color: "purple" },
        replied: { label: "Replied", value: 9876, icon: "💬", color: "orange" },
      },
      charts: {
        title: "Message Performance - Last 7 Days",
        labels: ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"],
      },
      topTemplates: {
        title: "Top Performing Templates",
        data: [
          { name: "Appointment Reminder - 24h", sent: 3456, rate: 95 },
          { name: "Booking Confirmation", sent: 2987, rate: 98 },
          { name: "Post-Visit Follow-up", sent: 1876, rate: 87 },
          { name: "Monthly Special Offer", sent: 1234, rate: 72 },
        ],
      },
      deliveryRate: "Delivery Rate",
      readRate: "Read Rate",
      responseRate: "Response Rate",
      avgResponseTime: "Avg Response Time",
      minutes: "min",
    },
  };

  const t = content[lang];

  // Animate statistics on mount
  useEffect(() => {
    const duration = 2000;
    const steps = 60;
    const interval = duration / steps;

    let currentStep = 0;
    const timer = setInterval(() => {
      currentStep++;
      const progress = currentStep / steps;

      setAnimatedStats({
        sent: Math.floor(t.stats.sent.value * progress),
        delivered: Math.floor(t.stats.delivered.value * progress),
        read: Math.floor(t.stats.read.value * progress),
        replied: Math.floor(t.stats.replied.value * progress),
      });

      if (currentStep >= steps) {
        clearInterval(timer);
        setAnimatedStats({
          sent: t.stats.sent.value,
          delivered: t.stats.delivered.value,
          read: t.stats.read.value,
          replied: t.stats.replied.value,
        });
      }
    }, interval);

    return () => clearInterval(timer);
  }, [t.stats]);

  const getColorClasses = (color: string) => {
    const colors = {
      blue: "from-blue-500 to-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300",
      green:
        "from-green-500 to-green-600 bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300",
      purple:
        "from-purple-500 to-purple-600 bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300",
      orange:
        "from-orange-500 to-orange-600 bg-orange-50 dark:bg-orange-900/20 text-orange-700 dark:text-orange-300",
    };
    return colors[color as keyof typeof colors] || colors.blue;
  };

  const calculatePercentage = (value: number, total: number) => {
    return ((value / total) * 100).toFixed(1);
  };

  return (
    <div className={`space-y-8 ${isRTL ? "text-right" : "text-left"}`}>
      {/* Header */}
      <div className="text-center space-y-3">
        <h3 className="text-3xl font-black text-brand-ink dark:text-white">
          {t.title}
        </h3>
        <p className="text-lg text-gray-600 dark:text-gray-300">{t.subtitle}</p>
      </div>

      {/* Stats Grid */}
      <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
        {Object.entries(t.stats).map(([key, stat]) => {
          const value = animatedStats[key as keyof typeof animatedStats];
          return (
            <div
              key={key}
              className={`relative overflow-hidden rounded-2xl p-6 shadow-lg transition-all hover:scale-105 ${getColorClasses(stat.color).split(" ").slice(2).join(" ")}`}
            >
              <div
                className={`absolute top-0 right-0 w-24 h-24 bg-gradient-to-br ${getColorClasses(stat.color).split(" ").slice(0, 2).join(" ")} opacity-20 rounded-full -mr-8 -mt-8`}
              ></div>
              <div className="relative space-y-3">
                <div className="text-4xl">{stat.icon}</div>
                <div>
                  <div className="text-4xl font-black">
                    {value.toLocaleString()}
                  </div>
                  <div className="text-sm font-medium mt-1">{stat.label}</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Performance Metrics */}
      <div className="grid md:grid-cols-3 gap-6">
        <div className="rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-lg">
          <div className="flex items-center justify-between mb-4">
            <span className="text-sm font-semibold text-gray-600 dark:text-gray-400">
              {t.deliveryRate}
            </span>
            <span className="text-2xl">📊</span>
          </div>
          <div className="text-3xl font-black text-brand-green mb-2">
            {calculatePercentage(animatedStats.delivered, animatedStats.sent)}%
          </div>
          <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
            <div
              className="bg-gradient-to-r from-brand-green to-emerald-500 h-2 rounded-full transition-all duration-1000"
              style={{
                width: `${calculatePercentage(animatedStats.delivered, animatedStats.sent)}%`,
              }}
            ></div>
          </div>
        </div>

        <div className="rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-lg">
          <div className="flex items-center justify-between mb-4">
            <span className="text-sm font-semibold text-gray-600 dark:text-gray-400">
              {t.readRate}
            </span>
            <span className="text-2xl">📖</span>
          </div>
          <div className="text-3xl font-black text-purple-600 dark:text-purple-400 mb-2">
            {calculatePercentage(animatedStats.read, animatedStats.delivered)}%
          </div>
          <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
            <div
              className="bg-gradient-to-r from-purple-500 to-purple-600 h-2 rounded-full transition-all duration-1000"
              style={{
                width: `${calculatePercentage(animatedStats.read, animatedStats.delivered)}%`,
              }}
            ></div>
          </div>
        </div>

        <div className="rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-lg">
          <div className="flex items-center justify-between mb-4">
            <span className="text-sm font-semibold text-gray-600 dark:text-gray-400">
              {t.responseRate}
            </span>
            <span className="text-2xl">💭</span>
          </div>
          <div className="text-3xl font-black text-orange-600 dark:text-orange-400 mb-2">
            {calculatePercentage(animatedStats.replied, animatedStats.read)}%
          </div>
          <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
            <div
              className="bg-gradient-to-r from-orange-500 to-orange-600 h-2 rounded-full transition-all duration-1000"
              style={{
                width: `${calculatePercentage(animatedStats.replied, animatedStats.read)}%`,
              }}
            ></div>
          </div>
        </div>
      </div>

      {/* Top Templates */}
      <div className="rounded-2xl bg-white dark:bg-slate-800 p-8 shadow-lg">
        <h4 className="text-xl font-bold text-brand-ink dark:text-white mb-6">
          {t.topTemplates.title}
        </h4>
        <div className="space-y-4">
          {t.topTemplates.data.map((template, index) => (
            <div key={index} className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="font-semibold text-gray-700 dark:text-gray-300">
                  {template.name}
                </span>
                <div className="flex items-center gap-4">
                  <span className="text-sm text-gray-500 dark:text-gray-400">
                    {template.sent.toLocaleString()} sent
                  </span>
                  <span className="text-sm font-bold text-brand-green">
                    {template.rate}%
                  </span>
                </div>
              </div>
              <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                <div
                  className="bg-gradient-to-r from-brand-green to-emerald-500 h-2 rounded-full transition-all"
                  style={{ width: `${template.rate}%` }}
                ></div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid md:grid-cols-2 gap-6">
        <div className="rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 p-8 text-white shadow-xl">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-semibold opacity-90 mb-2">
                {t.avgResponseTime}
              </div>
              <div className="text-5xl font-black">
                28<span className="text-3xl">{t.minutes}</span>
              </div>
            </div>
            <div className="text-6xl opacity-20">⚡</div>
          </div>
        </div>

        <div className="rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 p-8 text-white shadow-xl">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-semibold opacity-90 mb-2">
                {lang === "ar" ? "وقت ذروة الإرسال" : "Peak Sending Time"}
              </div>
              <div className="text-5xl font-black">
                10{lang === "ar" ? "ص" : "AM"}
              </div>
            </div>
            <div className="text-6xl opacity-20">🕐</div>
          </div>
        </div>
      </div>
    </div>
  );
}
