"use client";

import { useState, useEffect } from "react";
import {
  Plus,
  Calendar,
  Check,
  Clock,
  Bell,
  ArrowRight,
  DollarSign,
  TrendingUp,
  MessageSquare,
  CalendarClock,
  Users,
  Car,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import type {
  DashboardMetrics,
  ConversationItem,
  TabId,
} from "@/lib/types/dashboard.types";
import type { BookingDetail } from "./AppointmentDetailModal";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import VoiceAgentQuickLink from "./VoiceAgentQuickLink";

type DashboardDictionary = typeof dashboardEn;

interface OverviewTabProps {
  lang: Lang;
  dt: DashboardDictionary;
  isAr: boolean;
  metrics: DashboardMetrics | null;
  refreshing: boolean;
  conversations: ConversationItem[];
  todayBookings: BookingDetail[];
  pendingDemos: number;
  pendingDeposits: number;
  unreadMessages: number;
  onTabChange: (tab: TabId) => void;
  onSelectAppointment: (booking: BookingDetail) => void;
  onRescheduleAppointment: (booking: BookingDetail) => void;
  onCreateAppointment: () => void;
  userIndustry?: string | null;
}

export function OverviewTab({
  lang,
  dt,
  isAr,
  metrics,
  refreshing,
  conversations,
  todayBookings,
  pendingDemos,
  pendingDeposits,
  unreadMessages,
  onTabChange,
  onSelectAppointment,
  onRescheduleAppointment,
  onCreateAppointment,
  userIndustry,
}: OverviewTabProps) {
  const isMobility = userIndustry === "mobility_automotive";
  const isProperty = userIndustry === "property_facilities";

  // Fetch rental metrics for mobility industry
  const [rentalMetrics, setRentalMetrics] = useState<{
    totalRevenue: number;
    activeRentals: number;
    overdueRentals: number;
  } | null>(null);

  useEffect(() => {
    if (!isMobility) return;
    fetch("/api/dashboard/rentals")
      .then((r) => r.json())
      .then((data) => {
        if (data.success && Array.isArray(data.rentals)) {
          const rentals = data.rentals as {
            amountPaid?: number;
            status?: string;
          }[];
          const totalRevenue = rentals.reduce(
            (sum: number, r: { amountPaid?: number }) =>
              sum + (r.amountPaid || 0),
            0,
          );
          const activeRentals = rentals.filter(
            (r: { status?: string }) => r.status === "active",
          ).length;
          const overdueRentals = rentals.filter(
            (r: { status?: string }) => r.status === "overdue",
          ).length;
          setRentalMetrics({ totalRevenue, activeRentals, overdueRentals });
        }
      })
      .catch(() => {});
  }, [isMobility]);

  const metricCards = [
    {
      title: isAr ? "الإيرادات" : "Revenue",
      value: `${metrics?.revenue?.currency || "QAR"} ${(metrics?.revenue?.total || 0).toLocaleString()}`,
      subtitle: isAr ? "جميع المصادر" : "All sources",
      icon: <DollarSign className="w-5 h-5" />,
      gradient: "from-emerald-500 to-teal-600",
      bgGradient: "from-emerald-50 to-teal-50",
    },
    {
      title: isMobility
        ? isAr
          ? "الإيجارات النشطة"
          : "Active Rentals"
        : isAr
          ? "الحجوزات"
          : "Bookings",
      value: isMobility
        ? metrics?.rentals?.active || rentalMetrics?.activeRentals || 0
        : metrics?.bookings?.total || 0,
      subtitle: isMobility
        ? `${metrics?.rentals?.count || rentalMetrics?.overdueRentals || 0} ${isAr ? "إجمالي" : "total"}`
        : `${metrics?.bookings?.confirmed || 0} ${isAr ? "مؤكد" : "confirmed"}`,
      icon: isMobility ? (
        <Car className="w-5 h-5" />
      ) : (
        <Calendar className="w-5 h-5" />
      ),
      gradient: "from-blue-500 to-indigo-600",
      bgGradient: "from-blue-50 to-indigo-50",
    },
    {
      title: isAr ? "العملاء" : "Customers",
      value: metrics?.customers?.total || 0,
      subtitle: isAr ? "إجمالي العملاء" : "Total customers",
      icon: <Users className="w-5 h-5" />,
      gradient: "from-violet-500 to-purple-600",
      bgGradient: "from-violet-50 to-purple-50",
    },
    {
      title: isMobility
        ? isAr
          ? "متأخرة"
          : "Overdue"
        : isAr
          ? "التحويل"
          : "Conversion",
      value: isMobility
        ? metrics?.receivables?.overdueRentals || rentalMetrics?.overdueRentals || 0
        : `${metrics?.performance?.conversionRate || 0}%`,
      subtitle: isMobility
        ? isAr
          ? "تحتاج متابعة"
          : "Needs follow-up"
        : isAr
          ? "تجربة إلى حجز"
          : "Demo to booking",
      icon: <TrendingUp className="w-5 h-5" />,
      gradient: "from-amber-500 to-orange-600",
      bgGradient: "from-amber-50 to-orange-50",
    },
  ];

  return (
    <div className="space-y-6 animate-fadeIn">
      {/* Metrics Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {metricCards.map((card, index) => (
          <div
            key={index}
            className={`group relative overflow-hidden rounded-2xl bg-gradient-to-br ${card.bgGradient} p-5 shadow-sm hover:shadow-lg transition-all duration-300 ${refreshing ? "opacity-60" : ""}`}
            style={{ animationDelay: `${index * 100}ms` }}
          >
            <div className="absolute -right-4 -top-4 opacity-10 group-hover:opacity-20 transition-opacity">
              <div
                className={`w-24 h-24 rounded-full bg-gradient-to-br ${card.gradient}`}
              />
            </div>
            <div className="relative">
              <div
                className={`inline-flex p-2 rounded-xl bg-gradient-to-br ${card.gradient} shadow-lg mb-3`}
              >
                <span className="w-5 h-5 text-white">{card.icon}</span>
              </div>
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                {card.title}
              </p>
              <p className="mt-1 text-2xl font-bold text-slate-900 tracking-tight">
                {card.value}
              </p>
              <p className="mt-0.5 text-xs text-slate-500">{card.subtitle}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Quick Actions Bar */}
      <div className="flex flex-wrap gap-3">
        <button
          onClick={() =>
            isMobility
              ? onTabChange("appointments")
              : isProperty
                ? onTabChange("viewings")
                : onCreateAppointment()
          }
          className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-5 py-3 text-sm font-semibold text-white shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
        >
          <Plus className="w-4 h-4" />
          <span>
            {isMobility
              ? isAr
                ? "حجز جديد"
                : "New Rental"
              : isProperty
                ? isAr
                  ? "معاينة جديدة"
                  : "New Viewing"
                : isAr
                  ? "موعد جديد"
                  : "New Appointment"}
          </span>
        </button>
      </div>

      {/* Voice Agent Quick Link - Only shows when configured */}
      <VoiceAgentQuickLink lang={lang} />

      {/* Main Grid: Conversations + Today's Schedule */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Recent Conversations */}
        <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
          <div className="flex items-center justify-between p-5 border-b border-slate-100">
            <div>
              <h2 className="text-base font-bold text-slate-900">
                {dt.recentConversations}
              </h2>
              <p className="text-xs text-slate-500 mt-0.5">
                {dt.recentConversationsDesc}
              </p>
            </div>
            <button
              onClick={() => onTabChange("whatsapp")}
              className="text-xs font-semibold text-brand-green hover:text-brand-greenHover transition-colors"
            >
              {dt.viewAll} →
            </button>
          </div>
          <div className="p-3">
            {conversations.length === 0 ? (
              <div className="flex flex-col items-center justify-center rounded-xl bg-slate-50 py-12 text-center">
                <div className="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
                  <MessageSquare className="w-6 h-6 text-slate-400" />
                </div>
                <p className="text-sm font-medium text-slate-600">
                  {dt.noConversations}
                </p>
                <p className="mt-1 text-xs text-slate-400 max-w-[200px]">
                  {dt.noConversationsDesc}
                </p>
              </div>
            ) : (
              <div className="space-y-2">
                {conversations.slice(0, 5).map((conv) => (
                  <button
                    key={conv.id}
                    onClick={() => onTabChange("whatsapp")}
                    className="flex items-center gap-3 w-full rounded-xl p-3 text-left transition-all hover:bg-slate-50 group"
                  >
                    <div className="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 text-sm font-bold text-white shadow-md">
                      {conv.customerName?.charAt(0).toUpperCase() || "?"}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-2">
                        <p className="text-sm font-semibold text-slate-900 truncate group-hover:text-brand-green transition-colors">
                          {conv.customerName || conv.customerPhone}
                        </p>
                        {(conv.unreadCount ?? 0) > 0 && (
                          <span className="flex h-5 min-w-[20px] items-center justify-center rounded-full bg-brand-green px-1.5 text-xs font-bold text-white">
                            {conv.unreadCount}
                          </span>
                        )}
                      </div>
                      <p className="text-xs text-slate-500 truncate">
                        {conv.lastMessage}
                      </p>
                    </div>
                    <span
                      className="text-[10px] text-slate-400"
                      suppressHydrationWarning
                    >
                      {conv.lastMessageAt
                        ? new Date(conv.lastMessageAt).toLocaleTimeString(
                            isAr ? "ar-SA" : "en-US",
                            { hour: "2-digit", minute: "2-digit" },
                          )
                        : ""}
                    </span>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Today's Schedule */}
        <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
          <div className="flex items-center justify-between p-5 border-b border-slate-100">
            <div>
              <h2 className="text-base font-bold text-slate-900">
                {dt.todaysSchedule}
              </h2>
              <p
                className="text-xs text-slate-500 mt-0.5"
                suppressHydrationWarning
              >
                {new Date().toLocaleDateString(isAr ? "ar-SA" : "en-US", {
                  weekday: "long",
                  month: "short",
                  day: "numeric",
                })}
              </p>
            </div>
            <button
              onClick={() => onTabChange(isProperty ? "viewings" : "appointments")}
              className="text-xs font-semibold text-brand-green hover:text-brand-greenHover transition-colors"
            >
              {dt.viewAll} \u2192
            </button>
          </div>
          <div className="p-3">
            {todayBookings.length === 0 ? (
              <div className="flex flex-col items-center justify-center rounded-xl bg-slate-50 py-12 text-center">
                <div className="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
                  <Calendar className="w-6 h-6 text-slate-400" />
                </div>
                <p className="text-sm font-medium text-slate-600">
                  {isAr
                    ? "\u0644\u0627 \u062a\u0648\u062c\u062f \u0645\u0648\u0627\u0639\u064a\u062f \u0627\u0644\u064a\u0648\u0645"
                    : "No appointments today"}
                </p>
                <p className="mt-1 text-xs text-slate-400">
                  {isAr
                    ? "\u062c\u062f\u0648\u0644\u0643 \u0641\u0627\u0631\u063a"
                    : "Your schedule is clear"}
                </p>
              </div>
            ) : (
              <div className="space-y-2">
                {todayBookings.slice(0, 5).map((booking: BookingDetail) => {
                  const canReschedule =
                    booking.status === "pending" ||
                    booking.status === "confirmed";

                  return (
                    <div
                      key={booking.id}
                      className="w-full flex items-center gap-3 rounded-xl bg-slate-50 p-3 hover:bg-slate-100 hover:ring-2 hover:ring-brand-green/20 transition-all"
                    >
                      <div className="flex flex-col items-center justify-center w-14 rounded-lg bg-white border border-slate-200 py-2 flex-shrink-0">
                        <span className="text-sm font-bold text-brand-green">
                          {booking.appointmentTime}
                        </span>
                        <span className="text-[10px] text-slate-400">
                          {booking.duration}m
                        </span>
                      </div>
                      <button
                        onClick={() => onSelectAppointment(booking)}
                        className="flex-1 min-w-0 text-left"
                      >
                        <p className="text-sm font-semibold text-slate-900 truncate">
                          {booking.customerName}
                        </p>
                        <p className="text-xs text-slate-500 truncate">
                          {booking.service}
                        </p>
                      </button>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        {booking.depositPaid ? (
                          <span className="flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-1 text-xs font-semibold text-emerald-700">
                            <Check className="w-3 h-3" />
                            <span className="hidden sm:inline">
                              {isAr ? "\u0645\u062f\u0641\u0648\u0639" : "Paid"}
                            </span>
                          </span>
                        ) : booking.depositAmount ? (
                          <span className="flex items-center gap-1 rounded-full bg-amber-100 px-2.5 py-1 text-xs font-semibold text-amber-700">
                            <Clock className="w-3 h-3" />
                            <span className="hidden sm:inline">
                              {isAr ? "\u0645\u0639\u0644\u0642" : "Pending"}
                            </span>
                          </span>
                        ) : null}
                        {canReschedule && (
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              onRescheduleAppointment(booking);
                            }}
                            className="inline-flex items-center gap-1 rounded-lg border border-violet-200 bg-violet-50 px-2 py-1 text-xs font-medium text-violet-700 hover:bg-violet-100 hover:border-violet-300 transition-all"
                            title={
                              isAr
                                ? "\u0625\u0639\u0627\u062f\u0629 \u062c\u062f\u0648\u0644\u0629"
                                : "Reschedule"
                            }
                          >
                            <CalendarClock className="w-3 h-3" />
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Pending Actions Alert */}
      {(pendingDemos > 0 || pendingDeposits > 0 || unreadMessages > 0) && (
        <div className="rounded-2xl bg-gradient-to-r from-amber-50 via-orange-50 to-red-50 border border-amber-200/50 p-5">
          <div className="flex items-center gap-2 mb-4">
            <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-500 text-white">
              <Bell className="w-4 h-4" />
            </span>
            <h2 className="text-base font-bold text-slate-900">
              {dt.pendingActions}
            </h2>
          </div>
          <div className="grid gap-3 sm:grid-cols-3">
            {pendingDemos > 0 && (
              <button
                onClick={() => onTabChange(isProperty ? "viewings" : "appointments")}
                className="flex items-center justify-between rounded-xl bg-white border border-slate-200 p-4 shadow-sm hover:shadow-md hover:border-brand-green transition-all group"
              >
                <div>
                  <p className="text-xs font-medium text-slate-500">
                    {isAr ? "طلبات تجربة" : "Demo requests"}
                  </p>
                  <p className="text-2xl font-bold text-amber-600">
                    {pendingDemos}
                  </p>
                </div>
                <ArrowRight className="w-5 h-5 text-slate-300 group-hover:text-brand-green transition-colors" />
              </button>
            )}
            {pendingDeposits > 0 && (
              <button
                onClick={() => onTabChange(isProperty ? "viewings" : "appointments")}
                className="flex items-center justify-between rounded-xl bg-white border border-slate-200 p-4 shadow-sm hover:shadow-md hover:border-brand-green transition-all group"
              >
                <div>
                  <p className="text-xs font-medium text-slate-500">
                    {isAr ? "عربونات معلقة" : "Pending deposits"}
                  </p>
                  <p className="text-2xl font-bold text-orange-600">
                    {pendingDeposits}
                  </p>
                </div>
                <ArrowRight className="w-5 h-5 text-slate-300 group-hover:text-brand-green transition-colors" />
              </button>
            )}
            {unreadMessages > 0 && (
              <button
                onClick={() => onTabChange("whatsapp")}
                className="flex items-center justify-between rounded-xl bg-white border border-slate-200 p-4 shadow-sm hover:shadow-md hover:border-brand-green transition-all group"
              >
                <div>
                  <p className="text-xs font-medium text-slate-500">
                    {dt.unreadMessages}
                  </p>
                  <p className="text-2xl font-bold text-blue-600">
                    {unreadMessages}
                  </p>
                </div>
                <ArrowRight className="w-5 h-5 text-slate-300 group-hover:text-brand-green transition-colors" />
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export default OverviewTab;
