"use client";

import type { Lang } from "@/lib/config";
import type { VoiceAgentStats, RecentCall } from "./useVoiceAgentData";
import {
  Phone,
  PhoneIncoming,
  Calendar,
  Clock,
  TrendingUp,
  ArrowRight,
  User,
  CheckCircle2,
  XCircle,
  Settings,
  BarChart3,
} from "lucide-react";

interface VoiceAgentOverviewProps {
  lang: Lang;
  stats: VoiceAgentStats | null;
  recentCalls: RecentCall[];
  agentStatus: string;
  onViewCalls: () => void;
  onViewAnalytics: () => void;
  onViewSettings: () => void;
  onSelectCall: (callId: string) => void;
}

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 formatTimeAgo(timestamp: string, isAr: boolean): string {
  const diff = Date.now() - new Date(timestamp).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return isAr ? "الآن" : "Just now";
  if (mins < 60) return isAr ? `منذ ${mins} دقيقة` : `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return isAr ? `منذ ${hours} ساعة` : `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return isAr ? `منذ ${days} يوم` : `${days}d ago`;
}

export default function VoiceAgentOverview({
  lang,
  stats,
  recentCalls,
  agentStatus,
  onViewCalls,
  onViewAnalytics,
  onViewSettings,
  onSelectCall,
}: VoiceAgentOverviewProps) {
  const isAr = lang === "ar";

  const statCards = [
    {
      label: isAr ? "إجمالي المكالمات" : "Total Calls",
      value: stats?.totalCalls ?? 0,
      icon: Phone,
      color: "text-blue-600",
      bg: "bg-blue-50",
    },
    {
      label: isAr ? "مكالمات اليوم" : "Today's Calls",
      value: stats?.todayCalls ?? 0,
      icon: PhoneIncoming,
      color: "text-green-600",
      bg: "bg-green-50",
    },
    {
      label: isAr ? "مواعيد محجوزة" : "Appointments Booked",
      value: stats?.appointmentsBooked ?? 0,
      icon: Calendar,
      color: "text-purple-600",
      bg: "bg-purple-50",
    },
    {
      label: isAr ? "متوسط المدة" : "Avg Duration",
      value: stats?.avgCallDuration
        ? formatDuration(stats.avgCallDuration)
        : "0s",
      icon: Clock,
      color: "text-amber-600",
      bg: "bg-amber-50",
    },
  ];

  return (
    <div className="space-y-6">
      {/* Agent Status Banner */}
      <div className="bg-white rounded-2xl border border-slate-200 p-4 shadow-sm flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div
            className={`w-3 h-3 rounded-full ${
              agentStatus === "active"
                ? "bg-green-500 animate-pulse"
                : "bg-slate-300"
            }`}
          />
          <span className="text-sm font-medium text-slate-700">
            {agentStatus === "active"
              ? isAr
                ? "الوكيل الصوتي نشط"
                : "Voice Agent Active"
              : isAr
                ? "الوكيل الصوتي غير نشط"
                : "Voice Agent Inactive"}
          </span>
        </div>
        <div className="flex items-center gap-2">
          {stats?.weekCalls != null && (
            <span className="text-xs text-slate-400 flex items-center gap-1">
              <TrendingUp className="w-3 h-3" />
              {isAr
                ? `${stats.weekCalls} مكالمات هذا الأسبوع`
                : `${stats.weekCalls} calls this week`}
            </span>
          )}
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card, idx) => {
          const Icon = card.icon;
          return (
            <div
              key={idx}
              className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm"
            >
              <div className="flex items-center justify-between mb-3">
                <div
                  className={`w-10 h-10 rounded-xl ${card.bg} flex items-center justify-center`}
                >
                  <Icon className={`w-5 h-5 ${card.color}`} />
                </div>
              </div>
              <p className="text-2xl font-bold text-slate-900">{card.value}</p>
              <p className="text-xs text-slate-500 mt-1">{card.label}</p>
            </div>
          );
        })}
      </div>

      {/* Quick Actions + Recent Calls */}
      <div className="grid lg:grid-cols-3 gap-6">
        {/* Recent Calls */}
        <div className="lg:col-span-2 bg-white rounded-2xl border border-slate-200 shadow-sm">
          <div className="flex items-center justify-between p-5 pb-3">
            <h3 className="font-semibold text-slate-900">
              {isAr ? "المكالمات الأخيرة" : "Recent Calls"}
            </h3>
            <button
              onClick={onViewCalls}
              className="text-xs text-brand-green hover:text-brand-greenHover font-medium flex items-center gap-1 transition-colors"
            >
              {isAr ? "عرض الكل" : "View All"}
              <ArrowRight className="w-3 h-3" />
            </button>
          </div>

          {recentCalls.length === 0 ? (
            <div className="px-5 pb-5 text-center py-8">
              <Phone className="w-8 h-8 text-slate-300 mx-auto mb-2" />
              <p className="text-sm text-slate-400">
                {isAr ? "لا توجد مكالمات بعد" : "No calls yet"}
              </p>
            </div>
          ) : (
            <div className="divide-y divide-slate-50">
              {recentCalls.slice(0, 5).map((call) => (
                <button
                  key={call.id}
                  onClick={() => onSelectCall(call.id)}
                  className="w-full flex items-center gap-3 px-5 py-3 hover:bg-slate-50 transition-colors text-start"
                >
                  <div className="w-9 h-9 rounded-full bg-slate-100 flex items-center justify-center flex-shrink-0">
                    <User className="w-4 h-4 text-slate-500" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-slate-800 truncate">
                      {call.customerName ||
                        call.customerPhone ||
                        (isAr ? "متصل مجهول" : "Unknown Caller")}
                    </p>
                    <p className="text-xs text-slate-400">
                      {formatTimeAgo(call.timestamp, isAr)}
                      {call.duration > 0 &&
                        ` · ${formatDuration(call.duration)}`}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    {call.appointmentBooked && (
                      <span className="px-2 py-0.5 rounded-full bg-green-50 text-green-600 text-[10px] font-medium">
                        {isAr ? "محجوز" : "Booked"}
                      </span>
                    )}
                    {call.outcome === "completed" ? (
                      <CheckCircle2 className="w-4 h-4 text-green-500" />
                    ) : call.outcome === "failed" ? (
                      <XCircle className="w-4 h-4 text-red-400" />
                    ) : null}
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Quick Actions */}
        <div className="space-y-4">
          <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
            <h3 className="font-semibold text-slate-900 mb-4">
              {isAr ? "إجراءات سريعة" : "Quick Actions"}
            </h3>
            <div className="space-y-2">
              <button
                onClick={onViewAnalytics}
                className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-start"
              >
                <div className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center">
                  <BarChart3 className="w-4 h-4 text-blue-600" />
                </div>
                <div>
                  <p className="text-sm font-medium text-slate-800">
                    {isAr ? "عرض التحليلات" : "View Analytics"}
                  </p>
                  <p className="text-[11px] text-slate-400">
                    {isAr
                      ? "تقارير ورؤى تفصيلية"
                      : "Detailed reports & insights"}
                  </p>
                </div>
              </button>
              <button
                onClick={onViewCalls}
                className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-start"
              >
                <div className="w-9 h-9 rounded-lg bg-green-50 flex items-center justify-center">
                  <Phone className="w-4 h-4 text-green-600" />
                </div>
                <div>
                  <p className="text-sm font-medium text-slate-800">
                    {isAr ? "سجل المكالمات" : "Call History"}
                  </p>
                  <p className="text-[11px] text-slate-400">
                    {isAr ? "تصفح جميع المكالمات" : "Browse all conversations"}
                  </p>
                </div>
              </button>
              <button
                onClick={onViewSettings}
                className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-start"
              >
                <div className="w-9 h-9 rounded-lg bg-purple-50 flex items-center justify-center">
                  <Settings className="w-4 h-4 text-purple-600" />
                </div>
                <div>
                  <p className="text-sm font-medium text-slate-800">
                    {isAr ? "إعدادات الوكيل" : "Agent Settings"}
                  </p>
                  <p className="text-[11px] text-slate-400">
                    {isAr ? "ضبط اللغة والنبرة" : "Customize language & tone"}
                  </p>
                </div>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
