/**
 * Analytics Panel Component
 * Revenue trends, deposit tracking, booking performance, top services
 *
 * All metrics are computed client-side from the bookings array, filtered
 * by the selected period (7 / 30 / 90 days). The metrics prop is kept as
 * a fallback but is no longer the primary data source.
 */

"use client";

import { useState, useMemo } from "react";
import type { Lang } from "@/lib/config";
import type { BookingDetail } from "./AppointmentDetailModal";
import type { DashboardMetrics } from "@/lib/types/dashboard.types";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";

interface DailyRevenuePoint {
  date: string;
  revenue: number;
  count: number;
}

interface ServiceStat {
  service: string;
  count: number;
  revenue: number;
}

interface AnalyticsPanelProps {
  lang: Lang;
  metrics: DashboardMetrics | null;
  bookings: BookingDetail[];
}

export default function AnalyticsPanel({
  lang,
  metrics,
  bookings,
}: AnalyticsPanelProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const [period, setPeriod] = useState<"7" | "30" | "90">("30");

  // ---------------------------------------------------------------------------
  // Period-filtered bookings + all derived metrics (memoised)
  // ---------------------------------------------------------------------------
  const {
    filteredBookings: _filteredBookings,
    totalRevenue,
    depositsCollected,
    depositsPending,
    totalBookingsCount,
    completionRate,
    noShowRate,
    avgValue,
    dailyData,
    maxRevenue,
    topServices,
    sourceCounts,
    revenuePercentageChange,
  } = useMemo(() => {
    const now = new Date();
    const periodDays = parseInt(period);
    const periodStart = new Date(
      now.getTime() - periodDays * 24 * 60 * 60 * 1000,
    );

    // --- Filter bookings by period -------------------------------------------
    const filtered = bookings.filter((b) => {
      const date = new Date(b.appointmentDate);
      return date >= periodStart && date <= now;
    });

    // --- Revenue metrics -----------------------------------------------------
    const revenue = filtered
      .filter((b) => b.status === "confirmed" || b.status === "completed")
      .reduce((sum, b) => sum + (b.totalAmount || 0), 0);

    const depsCollected = filtered
      .filter((b) => b.depositPaid)
      .reduce((sum, b) => sum + (b.depositAmount || 0), 0);

    const depsPending = filtered
      .filter((b) => !b.depositPaid && (b.depositAmount || 0) > 0)
      .reduce((sum, b) => sum + (b.depositAmount || 0), 0);

    // --- Booking performance -------------------------------------------------
    const total = filtered.length;
    const completedCount = filtered.filter(
      (b) => b.status === "completed",
    ).length;
    const noShowCount = filtered.filter((b) => b.status === "no_show").length;
    const cancelledCount = filtered.filter(
      (b) => b.status === "cancelled",
    ).length;
    const resolvedCount = completedCount + noShowCount + cancelledCount;
    const compRate =
      resolvedCount > 0 ? Math.round((completedCount / resolvedCount) * 100) : 0;
    const nsRate =
      total > 0 ? Math.round((noShowCount / total) * 100) : 0;
    const avg = total > 0 ? Math.round(revenue / total) : 0;

    // --- Daily revenue chart data --------------------------------------------
    const daily: DailyRevenuePoint[] = [];
    for (let i = periodDays - 1; i >= 0; i--) {
      const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
      const dateStr = d.toISOString().split("T")[0];
      const dayBookings = filtered.filter((b) => {
        const bd = new Date(b.appointmentDate).toISOString().split("T")[0];
        return (
          bd === dateStr &&
          (b.status === "confirmed" || b.status === "completed")
        );
      });
      daily.push({
        date: dateStr,
        revenue: dayBookings.reduce((sum, b) => sum + (b.totalAmount || 0), 0),
        count: dayBookings.length,
      });
    }
    const maxRev = Math.max(...daily.map((d) => d.revenue), 1);

    // --- Top services --------------------------------------------------------
    const serviceRevMap: Record<string, { count: number; revenue: number }> = {};
    for (const b of filtered.filter(
      (bk) => bk.status === "confirmed" || bk.status === "completed",
    )) {
      if (!serviceRevMap[b.service]) {
        serviceRevMap[b.service] = { count: 0, revenue: 0 };
      }
      serviceRevMap[b.service].count++;
      serviceRevMap[b.service].revenue += b.depositPaid
        ? b.depositAmount || 0
        : 0;
    }
    const topSvc: ServiceStat[] = Object.entries(serviceRevMap)
      .map(([service, data]) => ({
        service,
        count: data.count,
        revenue: data.revenue,
      }))
      .sort((a, b) => b.revenue - a.revenue)
      .slice(0, 5);

    // --- Booking sources -----------------------------------------------------
    const srcCounts: Record<string, number> = {};
    for (const b of filtered) {
      const src = b.source || "unknown";
      srcCounts[src] = (srcCounts[src] || 0) + 1;
    }

    // --- Previous period revenue (for period-over-period comparison) --------
    const prevPeriodStart = new Date(
      now.getTime() - 2 * periodDays * 24 * 60 * 60 * 1000,
    );
    const prevPeriodEnd = new Date(
      now.getTime() - periodDays * 24 * 60 * 60 * 1000,
    );
    const prevFiltered = bookings.filter((b) => {
      const date = new Date(b.appointmentDate);
      return date >= prevPeriodStart && date < prevPeriodEnd;
    });
    const prevRevenue = prevFiltered
      .filter((b) => b.status === "confirmed" || b.status === "completed")
      .reduce((sum, b) => sum + (b.totalAmount || 0), 0);

    const revPercentChange =
      prevRevenue > 0
        ? ((revenue - prevRevenue) / prevRevenue) * 100
        : revenue > 0
          ? 100
          : null;

    return {
      filteredBookings: filtered,
      totalRevenue: revenue,
      depositsCollected: depsCollected,
      depositsPending: depsPending,
      totalBookingsCount: total,
      completionRate: compRate,
      noShowRate: nsRate,
      avgValue: avg,
      dailyData: daily,
      maxRevenue: maxRev,
      topServices: topSvc,
      sourceCounts: srcCounts,
      revenuePercentageChange: revPercentChange,
    };
  }, [bookings, period]);

  // ---------------------------------------------------------------------------
  // Upcoming appointments (next 7 days) — computed from ALL bookings, not
  // period-filtered, so users always see what's coming up regardless of the
  // selected analytics period.
  // ---------------------------------------------------------------------------
  const upcomingBookings = useMemo(() => {
    const now = new Date();
    const next7Days = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    return bookings.filter((b) => {
      const date = new Date(b.appointmentDate);
      return date >= now && date <= next7Days && b.status !== "cancelled";
    }).length;
  }, [bookings]);

  // ---------------------------------------------------------------------------
  // Revenue from non-booking sources (quotations, rentals) via metrics prop
  // ---------------------------------------------------------------------------
  const quotationRevenue = metrics?.quotations?.revenue ?? 0;
  const rentalRevenue = metrics?.rentals?.revenue ?? 0;
  const combinedRevenue =
    metrics?.totalCombinedRevenue ??
    totalRevenue + quotationRevenue + rentalRevenue;
  const paidQuotations = metrics?.quotations?.paid ?? 0;
  const activeRentals = metrics?.rentals?.active ?? 0;

  // ---------------------------------------------------------------------------
  // Render
  // ---------------------------------------------------------------------------
  return (
    <div className="space-y-6">
      {/* Revenue Summary Cards */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div className="rounded-xl bg-white p-5 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {dt.totalRevenue}
          </p>
          <p className="mt-2 text-3xl font-bold text-emerald-600">
            QAR {combinedRevenue.toLocaleString()}
          </p>
          <p className="mt-1 text-xs text-slate-500">
            {isAr ? `آخر ${period} يوم` : `Last ${period} days`}
            {(quotationRevenue > 0 || rentalRevenue > 0) && (
              <span className="text-slate-400">
                {" "}
                ({isAr ? "جميع المصادر" : "all sources"})
              </span>
            )}
          </p>
          {revenuePercentageChange !== null && (
            <p
              className={`mt-1 text-xs font-medium ${revenuePercentageChange >= 0 ? "text-emerald-600" : "text-red-600"}`}
            >
              {revenuePercentageChange >= 0 ? "\u2191" : "\u2193"}{" "}
              {Math.abs(revenuePercentageChange).toFixed(1)}%{" "}
              {isAr
                ? `مقارنة بالـ ${period} يوم السابقة`
                : `vs previous ${period} days`}
            </p>
          )}
        </div>

        <div className="rounded-xl bg-white p-5 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {dt.depositsCollected}
          </p>
          <p className="mt-2 text-3xl font-bold text-sky-600">
            QAR {depositsCollected.toLocaleString()}
          </p>
          <p className="mt-1 text-xs text-emerald-600 font-medium">
            {isAr ? "مدفوع" : "Paid"}
          </p>
        </div>

        <div className="rounded-xl bg-white p-5 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {dt.depositsPending}
          </p>
          <p className="mt-2 text-3xl font-bold text-amber-600">
            QAR {depositsPending.toLocaleString()}
          </p>
          <p className="mt-1 text-xs text-amber-600 font-medium">
            {isAr ? "قيد الانتظار" : "Awaiting payment"}
          </p>
        </div>
      </div>

      {/* Revenue Breakdown */}
      {(quotationRevenue > 0 || rentalRevenue > 0) && (
        <div className="rounded-xl bg-white p-5 shadow-sm">
          <h3 className="text-sm font-semibold text-slate-900 mb-3">
            {isAr ? "تفاصيل الإيرادات" : "Revenue Breakdown"}
          </h3>
          <div className="space-y-2">
            {totalRevenue > 0 && (
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">
                  {isAr ? "الحجوزات" : "Bookings"}
                </span>
                <span className="font-medium">
                  QAR {totalRevenue.toLocaleString()}
                </span>
              </div>
            )}
            {quotationRevenue > 0 && (
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">
                  {isAr ? "عروض الأسعار" : "Quotations"}
                </span>
                <span className="font-medium">
                  QAR {quotationRevenue.toLocaleString()}
                </span>
              </div>
            )}
            {rentalRevenue > 0 && (
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">
                  {isAr ? "التأجير" : "Rentals"}
                </span>
                <span className="font-medium">
                  QAR {rentalRevenue.toLocaleString()}
                </span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Outstanding Receivables */}
      {(metrics?.receivables?.total || 0) > 0 && (
        <div className="rounded-xl bg-amber-50 border border-amber-200 p-5 shadow-sm">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold text-amber-900">
              {isAr ? "المبالغ المستحقة" : "Outstanding Receivables"}
            </h3>
            <p className="text-xl font-bold text-amber-700">
              QAR {(metrics?.receivables?.total || 0).toLocaleString()}
            </p>
          </div>
          <div className="space-y-1 text-sm">
            {(metrics?.receivables?.unpaidQuotations || 0) > 0 && (
              <div className="flex justify-between text-amber-800">
                <span>{isAr ? "عروض أسعار غير مدفوعة" : "Unpaid quotations"}</span>
                <span>QAR {(metrics?.receivables?.unpaidQuotations ?? 0).toLocaleString()}</span>
              </div>
            )}
            {(metrics?.receivables?.pendingDeposits || 0) > 0 && (
              <div className="flex justify-between text-amber-800">
                <span>{isAr ? "إيداعات معلقة" : "Pending deposits"}</span>
                <span>QAR {(metrics?.receivables?.pendingDeposits ?? 0).toLocaleString()}</span>
              </div>
            )}
            {(metrics?.receivables?.overdueRentals || 0) > 0 && (
              <div className="flex justify-between text-amber-800">
                <span>{isAr ? "إيجارات متأخرة" : "Overdue rentals"}</span>
                <span>QAR {(metrics?.receivables?.overdueRentals ?? 0).toLocaleString()}</span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Booking Performance Stats */}
      <div className="grid gap-4 sm:grid-cols-4">
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {isAr ? "إجمالي الحجوزات" : "Total Bookings"}
          </p>
          <p className="mt-1 text-2xl font-bold text-slate-900">
            {totalBookingsCount}
          </p>
        </div>
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {isAr ? "معدل الإكمال" : "Completion Rate"}
          </p>
          <p className="mt-1 text-2xl font-bold text-emerald-600">
            {completionRate}%
          </p>
        </div>
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {isAr ? "معدل عدم الحضور" : "No-Show Rate"}
          </p>
          <p className="mt-1 text-2xl font-bold text-red-600">{noShowRate}%</p>
        </div>
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {isAr ? "متوسط قيمة الحجز" : "Avg Booking Value"}
          </p>
          <p className="mt-1 text-2xl font-bold text-sky-600">
            QAR {avgValue.toLocaleString()}
          </p>
        </div>
        {paidQuotations > 0 && (
          <div className="rounded-xl bg-white p-4 shadow-sm">
            <p className="text-xs font-medium text-slate-500 uppercase">
              {isAr ? "عروض أسعار مدفوعة" : "Paid Quotations"}
            </p>
            <p className="mt-1 text-2xl font-bold text-violet-600">
              {paidQuotations}
            </p>
          </div>
        )}
        {activeRentals > 0 && (
          <div className="rounded-xl bg-white p-4 shadow-sm">
            <p className="text-xs font-medium text-slate-500 uppercase">
              {isAr ? "إيجارات نشطة" : "Active Rentals"}
            </p>
            <p className="mt-1 text-2xl font-bold text-orange-600">
              {activeRentals}
            </p>
          </div>
        )}
      </div>

      {/* Quick Insights — Upcoming Appointments & Customer Growth */}
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {isAr ? "المواعيد القادمة (7 أيام)" : "Upcoming (7 days)"}
          </p>
          <p className="mt-1 text-2xl font-bold text-indigo-600">
            {upcomingBookings}
          </p>
        </div>
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <p className="text-xs font-medium text-slate-500 uppercase">
            {isAr ? "إجمالي العملاء" : "Total Customers"}
          </p>
          <p className="mt-1 text-2xl font-bold text-slate-900">
            {metrics?.customers?.total ?? 0}
          </p>
          {(metrics?.customers?.new ?? 0) > 0 && (
            <p className="mt-1 text-xs text-emerald-600 font-medium">
              +{metrics!.customers!.new}{" "}
              {isAr ? "جديد هذه الفترة" : "new this period"}
            </p>
          )}
        </div>
      </div>

      {/* Quotation Conversion Funnel */}
      {(metrics?.quotations?.count || 0) > 0 && (
        <div className="rounded-xl bg-white p-5 shadow-sm">
          <h3 className="text-base font-semibold text-slate-900 mb-4">
            {isAr ? "مسار عروض الأسعار" : "Quotation Pipeline"}
          </h3>
          <div className="space-y-3">
            {[
              { label: isAr ? "مسودة" : "Draft", count: metrics?.quotations?.draft || 0, color: "bg-slate-400" },
              { label: isAr ? "مرسل" : "Sent", count: metrics?.quotations?.sent || 0, color: "bg-sky-500" },
              { label: isAr ? "مقبول" : "Accepted", count: metrics?.quotations?.accepted || 0, color: "bg-amber-500" },
              { label: isAr ? "مدفوع" : "Paid", count: metrics?.quotations?.paid || 0, color: "bg-emerald-500" },
              { label: isAr ? "ملغي" : "Cancelled", count: metrics?.quotations?.cancelled || 0, color: "bg-red-400" },
            ].filter(stage => stage.count > 0).map((stage) => {
              const total = metrics?.quotations?.count || 1;
              const pct = Math.round((stage.count / total) * 100);
              return (
                <div key={stage.label}>
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm text-slate-700">{stage.label}</span>
                    <span className="text-sm font-semibold text-slate-900">{stage.count} ({pct}%)</span>
                  </div>
                  <div className="h-2 w-full rounded-full bg-slate-100 overflow-hidden">
                    <div className={`h-full ${stage.color} transition-all`} style={{ width: `${pct}%` }} />
                  </div>
                </div>
              );
            })}
          </div>
          <div className="mt-4 pt-3 border-t border-slate-100 flex gap-6 text-xs">
            <div>
              <span className="text-slate-500">{isAr ? "معدل التحويل" : "Conversion rate"}</span>
              <span className="ml-2 font-bold text-emerald-600">
                {(() => {
                  const sent = (metrics?.quotations?.sent || 0) + (metrics?.quotations?.accepted || 0) + (metrics?.quotations?.paid || 0);
                  return sent > 0 ? Math.round(((metrics?.quotations?.paid || 0) / sent) * 100) : 0;
                })()}%
              </span>
            </div>
            <div>
              <span className="text-slate-500">{isAr ? "معدل الإلغاء" : "Cancel rate"}</span>
              <span className="ml-2 font-bold text-red-500">
                {(() => {
                  const total = metrics?.quotations?.count || 1;
                  return Math.round(((metrics?.quotations?.cancelled || 0) / total) * 100);
                })()}%
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Revenue Trends Chart */}
      <div className="rounded-xl bg-white p-5 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-base font-semibold text-slate-900">
              {dt.revenueTrends}
            </h3>
            <p className="text-xs text-slate-500">
              {isAr
                ? "الإيرادات اليومية للفترة المختارة"
                : "Daily revenue for selected period"}
            </p>
          </div>
          <div className="flex gap-2">
            {[
              { value: "7" as const, label: dt.last7Days },
              { value: "30" as const, label: dt.last30Days },
              { value: "90" as const, label: dt.last90Days },
            ].map((option) => (
              <button
                key={option.value}
                onClick={() => setPeriod(option.value)}
                className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
                  period === option.value
                    ? "bg-brand-green text-white"
                    : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>

        {/* Bar chart with real data */}
        <div className="h-64 flex items-end justify-between gap-px rounded-lg border border-slate-100 bg-slate-50 p-4">
          {dailyData.map((day, index) => {
            const height = (day.revenue / maxRevenue) * 100;
            return (
              <div key={index} className="flex-1 flex flex-col items-center">
                <div
                  className="w-full rounded-t bg-gradient-to-t from-brand-green to-emerald-400 hover:from-emerald-600 hover:to-emerald-500 transition-all cursor-pointer min-h-[2px]"
                  style={{
                    height: `${Math.max(height, day.revenue > 0 ? 5 : 0)}%`,
                  }}
                  title={`${day.date}: QAR ${day.revenue.toLocaleString()} (${day.count} ${isAr ? "حجز" : "bookings"})`}
                />
              </div>
            );
          })}
        </div>
        <div className="mt-2 flex justify-between text-xs text-slate-500">
          <span>{isAr ? `قبل ${period} يوم` : `${period} days ago`}</span>
          <span>{isAr ? "اليوم" : "Today"}</span>
        </div>
      </div>

      {/* Top Services */}
      <div className="rounded-xl bg-white p-5 shadow-sm">
        <h3 className="mb-4 text-base font-semibold text-slate-900">
          {dt.topServices}
        </h3>
        <div className="space-y-3">
          {topServices.length === 0 ? (
            <p className="text-sm text-slate-500">
              {isAr ? "لا توجد بيانات بعد" : "No data yet"}
            </p>
          ) : (
            topServices.map((item, index) => (
              <div key={index} className="flex items-center justify-between">
                <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">
                      {item.service}
                    </p>
                    <p className="text-xs text-slate-500">
                      {item.count} {isAr ? "حجز" : "bookings"}
                    </p>
                  </div>
                </div>
                <p className="text-sm font-semibold text-emerald-700">
                  QAR {item.revenue.toLocaleString()}
                </p>
              </div>
            ))
          )}
        </div>
      </div>

      {/* Booking Sources */}
      <div className="rounded-xl bg-white p-5 shadow-sm">
        <h3 className="mb-4 text-base font-semibold text-slate-900">
          {dt.bookingSources}
        </h3>
        <div className="space-y-3">
          {(Object.entries(sourceCounts) as [string, number][]).map(([source, count]) => {
            const percentage =
              totalBookingsCount > 0
                ? Math.round((count / totalBookingsCount) * 100)
                : 0;
            const sourceLabels: Record<
              string,
              { label: string; color: string }
            > = {
              whatsapp: { label: dt.sourceWhatsApp, color: "bg-emerald-500" },
              manual: { label: dt.sourceManual, color: "bg-sky-500" },
              demo_booking: { label: dt.sourceDemo, color: "bg-violet-500" },
              widget: { label: dt.sourceWidget, color: "bg-orange-500" },
            };
            const sourceInfo = sourceLabels[source] || {
              label: source,
              color: "bg-slate-500",
            };

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

      {/* Export Data */}
      <div className="rounded-xl bg-gradient-to-r from-slate-50 to-slate-100 p-5 shadow-sm">
        <h3 className="mb-3 text-sm font-semibold text-slate-900">
          {dt.exportData}
        </h3>
        <div className="flex flex-wrap gap-2">
          <button className="rounded-lg bg-brand-green px-4 py-2 text-xs font-semibold text-white hover:bg-brand-greenHover">
            {dt.exportBookings}
          </button>
          <button className="rounded-lg bg-sky-600 px-4 py-2 text-xs font-semibold text-white hover:bg-sky-700">
            {dt.exportCustomers}
          </button>
          <button className="rounded-lg bg-violet-600 px-4 py-2 text-xs font-semibold text-white hover:bg-violet-700">
            {dt.exportRevenue}
          </button>
        </div>
      </div>
    </div>
  );
}
