/**
 * Real Estate Analytics Component
 * Dashboard metrics for properties, viewings, pipeline, trends, and broker performance
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import {
  Loader2,
  Eye,
  DollarSign,
  TrendingUp,
  Users,
  BarChart3,
  RefreshCw,
} from "lucide-react";

interface AnalyticsData {
  properties: {
    total: number;
    available: number;
    reserved: number;
    sold: number;
    rented: number;
    offMarket: number;
  };
  viewings: {
    active: number;
    completedThisMonth: number;
    cancelledThisMonth: number;
    monthlyTrend: number[];
  };
  pipeline: {
    totalValue: number;
    completedValue: number;
    averageDealSize: number;
    conversionRate: number;
  };
  brokerPerformance: {
    id: string;
    name: string;
    viewings: number;
    completed: number;
    conversionRate: number;
  }[];
}

interface RealEstateAnalyticsProps {
  lang: Lang;
}

export default function RealEstateAnalytics({
  lang,
}: RealEstateAnalyticsProps) {
  const isAr = lang === "ar";

  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);

  const fetchAnalytics = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/real-estate/analytics");
      const data = await res.json();
      if (data.success) {
        setAnalytics(data.analytics);
      }
    } catch (error) {
      console.error("Failed to fetch analytics:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAnalytics();
  }, [fetchAnalytics]);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await fetchAnalytics();
    setTimeout(() => setIsRefreshing(false), 500);
  };

  const formatPrice = (amount: number) => {
    return new Intl.NumberFormat(isAr ? "ar-SA" : "en-US", {
      style: "decimal",
      maximumFractionDigits: 0,
    }).format(amount);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-16">
        <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
      </div>
    );
  }

  if (!analytics) {
    return (
      <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm p-8 text-center">
        <BarChart3 className="w-12 h-12 text-slate-300 mx-auto mb-4" />
        <p className="text-sm font-medium text-slate-600">
          {isAr
            ? "لا تتوفر بيانات تحليلية بعد"
            : "No analytics data available yet"}
        </p>
        <p className="text-xs text-slate-400 mt-1">
          {isAr
            ? "أضف عقارات ومعاينات للبدء"
            : "Add properties and viewings to get started"}
        </p>
      </div>
    );
  }

  const MONTHS = isAr
    ? [
        "يناير",
        "فبراير",
        "مارس",
        "أبريل",
        "مايو",
        "يونيو",
        "يوليو",
        "أغسطس",
        "سبتمبر",
        "أكتوبر",
        "نوفمبر",
        "ديسمبر",
      ]
    : [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
      ];

  const maxTrend = Math.max(...(analytics.viewings.monthlyTrend || [1]), 1);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-slate-900">
            {isAr ? "تحليلات العقارات" : "Real Estate Analytics"}
          </h2>
          <p className="text-sm text-slate-500 mt-0.5">
            {isAr ? "ملخص أداء العقارات" : "Property performance overview"}
          </p>
        </div>
        <button
          onClick={handleRefresh}
          disabled={isRefreshing}
          className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 hover:border-slate-300 transition-all disabled:opacity-50"
        >
          <RefreshCw
            className={`w-3.5 h-3.5 ${isRefreshing ? "animate-spin" : ""}`}
          />
          {isAr ? "تحديث" : "Refresh"}
        </button>
      </div>

      {/* Property Status Metrics */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        <div className="rounded-xl bg-white border border-slate-200 p-4 text-center">
          <p className="text-2xl font-bold text-slate-800">
            {analytics.properties.total}
          </p>
          <p className="text-xs text-slate-500 mt-0.5">
            {isAr ? "إجمالي العقارات" : "Total Properties"}
          </p>
        </div>
        <div className="rounded-xl bg-emerald-50 border border-emerald-200 p-4 text-center">
          <p className="text-2xl font-bold text-emerald-700">
            {analytics.properties.available}
          </p>
          <p className="text-xs text-emerald-600 mt-0.5">
            {isAr ? "متاح" : "Available"}
          </p>
        </div>
        <div className="rounded-xl bg-amber-50 border border-amber-200 p-4 text-center">
          <p className="text-2xl font-bold text-amber-700">
            {analytics.properties.reserved}
          </p>
          <p className="text-xs text-amber-600 mt-0.5">
            {isAr ? "محجوز" : "Reserved"}
          </p>
        </div>
        <div className="rounded-xl bg-blue-50 border border-blue-200 p-4 text-center">
          <p className="text-2xl font-bold text-blue-700">
            {analytics.properties.sold}
          </p>
          <p className="text-xs text-blue-600 mt-0.5">
            {isAr ? "مباع" : "Sold"}
          </p>
        </div>
        <div className="rounded-xl bg-violet-50 border border-violet-200 p-4 text-center">
          <p className="text-2xl font-bold text-violet-700">
            {analytics.properties.rented}
          </p>
          <p className="text-xs text-violet-600 mt-0.5">
            {isAr ? "مؤجر" : "Rented"}
          </p>
        </div>
        <div className="rounded-xl bg-slate-100 border border-slate-200 p-4 text-center">
          <p className="text-2xl font-bold text-slate-600">
            {analytics.properties.offMarket}
          </p>
          <p className="text-xs text-slate-500 mt-0.5">
            {isAr ? "خارج السوق" : "Off Market"}
          </p>
        </div>
      </div>

      {/* Key Metrics Row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="rounded-2xl bg-gradient-to-br from-blue-500 to-blue-600 p-5 text-white shadow-lg shadow-blue-500/25">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/20">
              <Eye className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-white/70">
                {isAr ? "المعاينات النشطة" : "Active Viewings"}
              </p>
              <p className="text-2xl font-bold">{analytics.viewings.active}</p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl bg-gradient-to-br from-emerald-500 to-emerald-600 p-5 text-white shadow-lg shadow-emerald-500/25">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/20">
              <DollarSign className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-white/70">
                {isAr ? "قيمة خط الأنابيب" : "Pipeline Value"}
              </p>
              <p className="text-2xl font-bold">
                {formatPrice(analytics.pipeline.totalValue)} QAR
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl bg-gradient-to-br from-violet-500 to-violet-600 p-5 text-white shadow-lg shadow-violet-500/25">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/20">
              <TrendingUp className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-white/70">
                {isAr ? "معدل التحويل" : "Conversion Rate"}
              </p>
              <p className="text-2xl font-bold">
                {analytics.pipeline.conversionRate}%
              </p>
            </div>
          </div>
        </div>

        <div className="rounded-2xl bg-gradient-to-br from-amber-500 to-amber-600 p-5 text-white shadow-lg shadow-amber-500/25">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-white/20">
              <DollarSign className="w-5 h-5" />
            </div>
            <div>
              <p className="text-xs font-medium text-white/70">
                {isAr ? "متوسط حجم الصفقة" : "Avg Deal Size"}
              </p>
              <p className="text-2xl font-bold">
                {formatPrice(analytics.pipeline.averageDealSize)} QAR
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Monthly Viewing Trend */}
      <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm p-6">
        <h3 className="text-sm font-bold text-slate-800 mb-4">
          {isAr ? "اتجاه المعاينات الشهري" : "Monthly Viewing Trend"}
        </h3>
        <div className="flex items-end gap-2 h-40">
          {(analytics.viewings.monthlyTrend || []).map((count, idx) => (
            <div
              key={idx}
              className="flex-1 flex flex-col items-center justify-end gap-1"
            >
              <span className="text-[10px] font-semibold text-slate-500">
                {count}
              </span>
              <div
                className="w-full rounded-t-lg bg-gradient-to-t from-brand-green to-emerald-400 transition-all duration-500"
                style={{
                  height: `${(count / maxTrend) * 100}%`,
                  minHeight: count > 0 ? "4px" : "0",
                }}
              />
              <span className="text-[10px] text-slate-400 mt-1">
                {MONTHS[idx]}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Broker Performance */}
      {analytics.brokerPerformance.length > 0 && (
        <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
          <div className="p-5 border-b border-slate-100">
            <h3 className="flex items-center gap-2 text-sm font-bold text-slate-800">
              <Users className="w-4 h-4 text-slate-500" />
              {isAr ? "أداء الوسطاء" : "Broker Performance"}
            </h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-slate-50">
                  <th className="px-5 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">
                    {isAr ? "الوسيط" : "Broker"}
                  </th>
                  <th className="px-5 py-3 text-center text-xs font-bold text-slate-500 uppercase tracking-wider">
                    {isAr ? "المعاينات" : "Viewings"}
                  </th>
                  <th className="px-5 py-3 text-center text-xs font-bold text-slate-500 uppercase tracking-wider">
                    {isAr ? "المكتملة" : "Completed"}
                  </th>
                  <th className="px-5 py-3 text-center text-xs font-bold text-slate-500 uppercase tracking-wider">
                    {isAr ? "التحويل" : "Conv. Rate"}
                  </th>
                  <th className="px-5 py-3 text-right text-xs font-bold text-slate-500 uppercase tracking-wider">
                    {isAr ? "الأداء" : "Performance"}
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {analytics.brokerPerformance.map((broker) => (
                  <tr
                    key={broker.id}
                    className="hover:bg-slate-50/50 transition-colors"
                  >
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-full bg-gradient-to-br from-brand-green to-emerald-600 flex items-center justify-center text-white text-xs font-bold">
                          {broker.name.charAt(0).toUpperCase()}
                        </div>
                        <span className="text-sm font-semibold text-slate-900">
                          {broker.name}
                        </span>
                      </div>
                    </td>
                    <td className="px-5 py-4 text-center text-sm text-slate-700">
                      {broker.viewings}
                    </td>
                    <td className="px-5 py-4 text-center text-sm text-slate-700">
                      {broker.completed}
                    </td>
                    <td className="px-5 py-4 text-center">
                      <span
                        className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold ${
                          broker.conversionRate >= 50
                            ? "bg-emerald-100 text-emerald-700"
                            : broker.conversionRate >= 25
                              ? "bg-amber-100 text-amber-700"
                              : "bg-red-100 text-red-700"
                        }`}
                      >
                        {broker.conversionRate}%
                      </span>
                    </td>
                    <td className="px-5 py-4">
                      <div className="flex items-center justify-end gap-2">
                        <div className="w-24 h-2 bg-slate-100 rounded-full overflow-hidden">
                          <div
                            className="h-full rounded-full bg-gradient-to-r from-brand-green to-emerald-400"
                            style={{
                              width: `${Math.min(broker.conversionRate, 100)}%`,
                            }}
                          />
                        </div>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
