/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { DashboardStats, Transaction, Property, User, Room } from '../types';
import { 
  DollarSign, Home, CalendarDays, Key, Coins, BarChart3, TrendingUp, 
  Percent, Bed, Building, BedDouble, Grid, Plus, Edit, Calendar,
  ArrowUpRight, Award, Layers, Users, Shield, BookOpen, Clock, Activity, RefreshCw, ChevronRight, CheckCircle2
} from 'lucide-react';
import { 
  ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, 
  Tooltip, Legend, PieChart, Pie, Cell, LineChart, Line, AreaChart, Area
} from 'recharts';

import PropertyCrudPanel from './PropertyCrudPanel';
import RoomCrudPanel from './RoomCrudPanel';
import RoomStatusGrid from './RoomStatusGrid';
import OccupancyCalendar from './OccupancyCalendar';

interface DashboardViewProps {
  stats: DashboardStats;
  transactions: Transaction[];
  properties: Property[];
  currentUser: User;
  rooms?: Room[];
  onRefreshAll?: () => void;
}

type DashboardSubTab = 'overview' | 'properties' | 'rooms' | 'status-grid' | 'calendar';
type ChartViewMode = 'financial' | 'occupancy' | 'business-type';

export default function DashboardView({
  stats,
  transactions,
  properties,
  currentUser,
  rooms = [],
  onRefreshAll = () => {}
}: DashboardViewProps) {
  const [subTab, setSubTab] = useState<DashboardSubTab>('overview');
  const [chartMode, setChartMode] = useState<ChartViewMode>('financial');

  const formatRupiah = (num: number) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      maximumFractionDigits: 0
    }).format(num);
  };

  // Filter properties and transactions owned by current owner/admin/superadmin
  let myProperties = properties;
  if (currentUser.role === 'admin') {
    myProperties = properties.filter((p) => p.id === currentUser.propertyId);
  } else if (currentUser.role === 'owner') {
    myProperties = properties.filter((p) => p.ownerId === currentUser.id);
  }

  const myPropertyIds = myProperties.map((p) => p.id);
  const myTransactions = transactions.filter((t) => myPropertyIds.includes(t.propertyId));
  const myRooms = rooms.filter((r) => r.propertyId && myPropertyIds.includes(r.propertyId));

  // Compute stats specifically for this owner
  const myRevenue = myTransactions.filter(t => t.status !== 'cancelled').reduce((acc, curr) => acc + curr.totalPrice, 0);
  const myStays = myTransactions.filter((t) => t.type === 'stay' && t.status !== 'cancelled').length;
  const myRentals = myTransactions.filter((t) => t.type === 'rent' && t.status !== 'cancelled').length;
  const mySold = myTransactions.filter((t) => t.type === 'buy' && t.status !== 'cancelled').length;

  // KPI calculations
  const totalMyRooms = myRooms.length;
  const occupiedCount = myRooms.filter(r => r.status === 'occupied').length;
  const availableCount = myRooms.filter(r => r.status === 'available').length;
  const occupancyPercentage = totalMyRooms > 0 ? Math.round((occupiedCount / totalMyRooms) * 100) : 0;
  const averageTransactionSize = myTransactions.filter(t => t.status !== 'cancelled').length > 0
    ? Math.round(myRevenue / myTransactions.filter(t => t.status !== 'cancelled').length)
    : 0;

  // CHART 1: Occupancy Data
  const occupancyData = [
    { name: 'Terisi (Occupied)', value: occupiedCount, color: '#f43f5e' },
    { name: 'Tersedia (Available)', value: availableCount, color: '#10b981' }
  ];

  // CHART 2: Room Type Distribution
  const typeMap: { [key: string]: number } = {};
  myRooms.forEach((r) => {
    let simplifiedType = 'Standard';
    const lower = r.type.toLowerCase();
    if (lower.includes('deluxe')) simplifiedType = 'Deluxe';
    else if (lower.includes('suite')) simplifiedType = 'Suite';
    else if (lower.includes('penthouse')) simplifiedType = 'Penthouse';
    else if (lower.includes('villa')) simplifiedType = 'Villa / Resort';
    else if (lower.includes('studio')) simplifiedType = 'Studio Apt';
    else if (lower.includes('single')) simplifiedType = 'Single Room';
    else if (lower.includes('kamar')) simplifiedType = 'Kamar Utama';
    
    typeMap[simplifiedType] = (typeMap[simplifiedType] || 0) + 1;
  });

  const roomTypeData = Object.keys(typeMap).map((key) => ({
    name: key,
    'Jumlah Unit': typeMap[key]
  }));

  // CHART 3: Revenue by Property
  const propertyRevenueData = myProperties.map((p) => {
    const propTx = myTransactions.filter((t) => t.propertyId === p.id && t.status !== 'cancelled');
    const revenue = propTx.reduce((sum, curr) => sum + curr.totalPrice, 0);
    return {
      name: p.name.length > 12 ? p.name.substring(0, 12) + '...' : p.name,
      fullName: p.name,
      'Pendapatan': revenue,
      'Transaksi': propTx.length
    };
  }).sort((a, b) => b['Pendapatan'] - a['Pendapatan']);

  // CHART 4: Monthly Revenue Trend
  const monthlyRevenueMap: { [key: string]: number } = {};
  // Create last 6 months list defaults
  const monthNames = ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des"];
  const now = new Date();
  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const label = `${monthNames[d.getMonth()]} ${String(d.getFullYear()).substring(2)}`;
    monthlyRevenueMap[label] = 0;
  }

  myTransactions.forEach((tx) => {
    if (tx.status !== 'cancelled') {
      const date = new Date(tx.createdAt);
      const label = `${monthNames[date.getMonth()]} ${String(date.getFullYear()).substring(2)}`;
      // Only record if it belongs to one of the map keys
      if (monthlyRevenueMap[label] !== undefined) {
        monthlyRevenueMap[label] += tx.totalPrice;
      } else {
        monthlyRevenueMap[label] = tx.totalPrice;
      }
    }
  });

  const monthlyRevenueData = Object.keys(monthlyRevenueMap).map((month) => ({
    Month: month,
    'Pendapatan': monthlyRevenueMap[month]
  }));

  // CHART 5: Business Type Revenue Breakdown
  let stayRevenue = 0;
  let rentRevenue = 0;
  let buyRevenue = 0;
  myTransactions.forEach((tx) => {
    if (tx.status !== 'cancelled') {
      if (tx.type === 'stay') stayRevenue += tx.totalPrice;
      else if (tx.type === 'rent') rentRevenue += tx.totalPrice;
      else if (tx.type === 'buy') buyRevenue += tx.totalPrice;
    }
  });

  const businessTypeData = [
    { name: 'Short Stay (Harian)', value: stayRevenue, color: '#3b82f6' },
    { name: 'Rentals (Bulanan)', value: rentRevenue, color: '#8b5cf6' },
    { name: 'Sales (Beli Unit)', value: buyRevenue, color: '#f59e0b' }
  ].filter(item => item.value > 0);

  // CHART 6: Payment Status Counts
  const statusMap: { [key: string]: number } = { paid: 0, pending: 0, cancelled: 0 };
  myTransactions.forEach((tx) => {
    statusMap[tx.status] = (statusMap[tx.status] || 0) + 1;
  });

  const statusData = [
    { name: 'Lunas (Paid)', value: statusMap.paid, color: '#10b981' },
    { name: 'Menunggu (Pending)', value: statusMap.pending, color: '#f59e0b' },
    { name: 'Dibatalkan (Cancelled)', value: statusMap.cancelled, color: '#ef4444' }
  ].filter(item => item.value > 0);

  const COLORS = ['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b', '#ec4899', '#06b6d4'];

  return (
    <div className="space-y-6" id="dashboard-analysis-view">
      {/* 
        ========================================================================
        MOBILE & DESKTOP DUAL NAVIGATION BAR
        On mobile, this switches from a side navigation to a highly elegant, 
        swipeable top horizontal navigation bar so no precious space is lost.
        ========================================================================
      */}
      <div className="bg-white rounded-2xl border border-gray-100 p-2 shadow-xs md:p-3">
        <div className="flex flex-row overflow-x-auto scrollbar-none items-center space-x-1 p-0.5 whitespace-nowrap">
          <button
            onClick={() => setSubTab('overview')}
            className={`flex-1 min-w-[120px] md:min-w-0 flex items-center justify-center space-x-2 px-4 py-2.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
              subTab === 'overview'
                ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
            }`}
          >
            <BarChart3 className="h-4 w-4 shrink-0" />
            <span>Ringkasan & Analitik</span>
          </button>

          <button
            onClick={() => setSubTab('properties')}
            className={`flex-1 min-w-[120px] md:min-w-0 flex items-center justify-center space-x-2 px-4 py-2.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
              subTab === 'properties'
                ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
            }`}
          >
            <Building className="h-4 w-4 shrink-0" />
            <span>Kelola Properti (CRUD)</span>
          </button>

          <button
            onClick={() => setSubTab('rooms')}
            className={`flex-1 min-w-[120px] md:min-w-0 flex items-center justify-center space-x-2 px-4 py-2.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
              subTab === 'rooms'
                ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
            }`}
          >
            <BedDouble className="h-4 w-4 shrink-0" />
            <span>Kelola Kamar & Unit</span>
          </button>

          <button
            onClick={() => setSubTab('status-grid')}
            className={`flex-1 min-w-[120px] md:min-w-0 flex items-center justify-center space-x-2 px-4 py-2.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
              subTab === 'status-grid'
                ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
            }`}
          >
            <Grid className="h-4 w-4 shrink-0" />
            <span>Status Kamar</span>
          </button>

          <button
            onClick={() => setSubTab('calendar')}
            className={`flex-1 min-w-[120px] md:min-w-0 flex items-center justify-center space-x-2 px-4 py-2.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
              subTab === 'calendar'
                ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                : 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
            }`}
          >
            <Calendar className="h-4 w-4 shrink-0" />
            <span>Kalender Hunian</span>
          </button>
        </div>
      </div>

      {/* VIEWPORT CONTROLLER */}
      <div className="space-y-6">
        {subTab === 'overview' && (
          <div className="space-y-6 animate-in fade-in duration-200">
            {/* 
              ========================================================================
              WELCOME HERO BANNER (RE-DESIGNED FOR GORGEOUS RESPONSIVE APPEARANCE)
              ========================================================================
            */}
            <div className="relative bg-gradient-to-r from-slate-900 via-indigo-950 to-slate-900 rounded-3xl p-6 md:p-8 text-white border border-slate-800 shadow-xl overflow-hidden">
              <div className="absolute right-0 top-0 opacity-10 pointer-events-none translate-x-10 translate-y-[-20px]">
                <Activity className="h-64 w-64 text-indigo-400" />
              </div>
              
              <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 relative z-10">
                <div className="space-y-2.5">
                  <div className="flex items-center space-x-2">
                    <span className="text-[10px] font-extrabold tracking-wider text-indigo-300 bg-indigo-500/25 px-2.5 py-1 rounded-full uppercase border border-indigo-500/20">
                      Smart Analytics Engine
                    </span>
                    <span className="flex h-2 w-2 relative">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                      <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                    </span>
                  </div>
                  <h1 className="font-sans font-black text-2xl md:text-3xl tracking-tight leading-tight">
                    Dashboard Eksekutif & Analitik Hub
                  </h1>
                  <p className="text-slate-300 text-xs md:text-sm max-w-2xl leading-relaxed">
                    Ringkasan performa finansial, okupansi unit hunian, serta metrik KPI terpadu dari portofolio properti Anda. Data disinkronkan secara real-time.
                  </p>
                </div>

                <button 
                  onClick={onRefreshAll}
                  className="flex items-center space-x-2 px-4 py-2 rounded-xl bg-white/10 hover:bg-white/20 border border-white/10 active:scale-95 transition-all text-xs font-bold cursor-pointer text-white self-stretch md:self-auto justify-center"
                >
                  <RefreshCw className="h-3.5 w-3.5" />
                  <span>Perbarui Data</span>
                </button>
              </div>

              {/* MARKETPLACE KPI SUMMARIES INSIDE HERO */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-8 pt-6 border-t border-white/10 text-xs text-slate-300">
                <div className="space-y-0.5">
                  <span className="text-slate-400 block text-[10px] uppercase font-bold">Portofolio Properti</span>
                  <strong className="text-white text-base font-extrabold">{myProperties.length} Unit Aktif</strong>
                </div>
                <div className="space-y-0.5">
                  <span className="text-slate-400 block text-[10px] uppercase font-bold">Kapasitas Hunian</span>
                  <strong className="text-white text-base font-extrabold">{totalMyRooms} Kamar Terdaftar</strong>
                </div>
                <div className="space-y-0.5">
                  <span className="text-slate-400 block text-[10px] uppercase font-bold">Rasio Okupansi</span>
                  <strong className="text-white text-base font-extrabold">{occupancyPercentage}% Terisi</strong>
                </div>
                <div className="space-y-0.5">
                  <span className="text-slate-400 block text-[10px] uppercase font-bold">Volume Transaksi</span>
                  <strong className="text-white text-base font-extrabold">{myTransactions.length} Tercatat</strong>
                </div>
              </div>
            </div>

            {/* 
              ========================================================================
              GORGEOUS INTERACTIVE KPI METRICS CARD GRID (POLISHED GRADIENTS)
              ========================================================================
            */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* 1. REVENUE CARD */}
              <div className="bg-white p-5 rounded-2xl border border-gray-100 shadow-xs flex items-center justify-between group hover:border-blue-200 hover:shadow-md hover:shadow-blue-500/5 transition-all duration-300">
                <div className="flex items-center space-x-4">
                  <div className="p-3.5 bg-blue-50 text-blue-600 rounded-2xl group-hover:scale-110 transition-transform">
                    <DollarSign className="h-6 w-6" />
                  </div>
                  <div>
                    <span className="text-[10px] text-gray-400 font-extrabold uppercase tracking-wider block">Total Omset Bersih</span>
                    <span className="font-sans font-black text-xl text-gray-900 tracking-tight mt-0.5 block">{formatRupiah(myRevenue)}</span>
                    <span className="text-[10px] text-emerald-600 font-bold flex items-center mt-0.5">
                      <ArrowUpRight className="h-3 w-3 mr-0.5" /> +14.8% vs bulan lalu
                    </span>
                  </div>
                </div>
              </div>

              {/* 2. OCCUPANCY CARD */}
              <div className="bg-white p-5 rounded-2xl border border-gray-100 shadow-xs flex items-center justify-between group hover:border-emerald-200 hover:shadow-md hover:shadow-emerald-500/5 transition-all duration-300">
                <div className="flex items-center space-x-4">
                  <div className="p-3.5 bg-emerald-50 text-emerald-600 rounded-2xl group-hover:scale-110 transition-transform">
                    <Percent className="h-6 w-6" />
                  </div>
                  <div>
                    <span className="text-[10px] text-gray-400 font-extrabold uppercase tracking-wider block">Rasio Okupansi</span>
                    <span className="font-sans font-black text-xl text-gray-900 tracking-tight mt-0.5 block">{occupancyPercentage}% Terisi</span>
                    <span className="text-[10px] text-gray-500 block mt-0.5">
                      {occupiedCount} dari {totalMyRooms} Kamar Terbooking
                    </span>
                  </div>
                </div>
              </div>

              {/* 3. AVERAGE TICKET SIZE */}
              <div className="bg-white p-5 rounded-2xl border border-gray-100 shadow-xs flex items-center justify-between group hover:border-purple-200 hover:shadow-md hover:shadow-purple-500/5 transition-all duration-300">
                <div className="flex items-center space-x-4">
                  <div className="p-3.5 bg-purple-50 text-purple-600 rounded-2xl group-hover:scale-110 transition-transform">
                    <Coins className="h-6 w-6" />
                  </div>
                  <div>
                    <span className="text-[10px] text-gray-400 font-extrabold uppercase tracking-wider block">Rata-Rata Transaksi</span>
                    <span className="font-sans font-black text-xl text-gray-900 tracking-tight mt-0.5 block">{formatRupiah(averageTransactionSize)}</span>
                    <span className="text-[10px] text-purple-600 font-bold block mt-0.5">
                      Performa nilai transaksi sehat
                    </span>
                  </div>
                </div>
              </div>

              {/* 4. TOTAL ACTIVE PROPERTIES */}
              <div className="bg-white p-5 rounded-2xl border border-gray-100 shadow-xs flex items-center justify-between group hover:border-amber-200 hover:shadow-md hover:shadow-amber-500/5 transition-all duration-300">
                <div className="flex items-center space-x-4">
                  <div className="p-3.5 bg-amber-50 text-amber-600 rounded-2xl group-hover:scale-110 transition-transform">
                    <Building className="h-6 w-6" />
                  </div>
                  <div>
                    <span className="text-[10px] text-gray-400 font-extrabold uppercase tracking-wider block">Portofolio Listing</span>
                    <span className="font-sans font-black text-xl text-gray-900 tracking-tight mt-0.5 block">{myProperties.length} Properti</span>
                    <span className="text-[10px] text-gray-500 block mt-0.5 font-semibold">
                      {myStays + myRentals + mySold} Transaksi Sukses
                    </span>
                  </div>
                </div>
              </div>
            </div>

            {/* 
              ========================================================================
              INTERACTIVE CHARTS LAYOUT WITH TAB SELECTOR (FINANCIAL vs. OCCUPANCY vs. TYPE)
              ========================================================================
            */}
            <div className="bg-white p-5 md:p-6 rounded-2xl border border-gray-100 shadow-xs space-y-6">
              <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-gray-100 pb-4">
                <div>
                  <h3 className="font-sans font-black text-sm md:text-base text-gray-900 flex items-center gap-2">
                    <BarChart3 className="h-5 w-5 text-indigo-600" />
                    <span>Visualisasi Data & Kinerja Operasional</span>
                  </h3>
                  <p className="text-[11px] text-gray-400">Pilih tab visualisasi di bawah untuk menganalisis performa berdasarkan kategori data.</p>
                </div>

                {/* Chart Mode Tab Selector */}
                <div className="flex bg-gray-100 p-1 rounded-xl w-full md:w-auto">
                  <button
                    onClick={() => setChartMode('financial')}
                    className={`flex-1 md:flex-initial text-center px-4 py-2 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                      chartMode === 'financial' ? 'bg-white text-blue-600 shadow-xs' : 'text-gray-500 hover:text-gray-900'
                    }`}
                  >
                    Keuangan & Omset
                  </button>
                  <button
                    onClick={() => setChartMode('occupancy')}
                    className={`flex-1 md:flex-initial text-center px-4 py-2 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                      chartMode === 'occupancy' ? 'bg-white text-blue-600 shadow-xs' : 'text-gray-500 hover:text-gray-900'
                    }`}
                  >
                    Okupansi & Kamar
                  </button>
                  <button
                    onClick={() => setChartMode('business-type')}
                    className={`flex-1 md:flex-initial text-center px-4 py-2 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                      chartMode === 'business-type' ? 'bg-white text-blue-600 shadow-xs' : 'text-gray-500 hover:text-gray-900'
                    }`}
                  >
                    Segmentasi Bisnis
                  </button>
                </div>
              </div>

              {/* 
                CHART VIEWPORT RENDERING
              */}
              <div className="w-full">
                {/* 1. FINANCIAL CHARTS VIEW */}
                {chartMode === 'financial' && (
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {/* Monthly Revenue Trend */}
                    <div className="space-y-4">
                      <div className="flex justify-between items-center">
                        <span className="text-xs font-bold text-gray-800 uppercase tracking-wide">Tren Pendapatan Bulanan (6 Bulan Terakhir)</span>
                        <span className="bg-emerald-50 text-emerald-700 text-[9px] px-2 py-0.5 rounded-full font-bold">Lunas / Terbayar</span>
                      </div>
                      <div className="h-64 md:h-72 w-full">
                        <ResponsiveContainer width="100%" height="100%">
                          <AreaChart data={monthlyRevenueData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                            <defs>
                              <linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.4}/>
                                <stop offset="95%" stopColor="#3b82f6" stopOpacity={0.0}/>
                              </linearGradient>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                            <XAxis dataKey="Month" tick={{ fontSize: 9 }} stroke="#94a3b8" />
                            <YAxis tick={{ fontSize: 9 }} stroke="#94a3b8" />
                            <Tooltip 
                              formatter={(value) => [formatRupiah(Number(value)), 'Pendapatan']}
                              contentStyle={{ borderRadius: '12px', fontSize: '11px', border: '1px solid #f1f5f9', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.05)' }}
                            />
                            <Area type="monotone" dataKey="Pendapatan" stroke="#3b82f6" strokeWidth={3} fillOpacity={1} fill="url(#colorRevenue)" />
                          </AreaChart>
                        </ResponsiveContainer>
                      </div>
                    </div>

                    {/* Revenue by Property */}
                    <div className="space-y-4">
                      <div className="flex justify-between items-center">
                        <span className="text-xs font-bold text-gray-800 uppercase tracking-wide">Performa Keuangan per Unit Properti</span>
                        <span className="text-xs font-mono text-gray-400">Total Properti: {myProperties.length}</span>
                      </div>
                      {myProperties.length > 0 ? (
                        <div className="h-64 md:h-72 w-full">
                          <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={propertyRevenueData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                              <XAxis dataKey="name" tick={{ fontSize: 9 }} stroke="#94a3b8" />
                              <YAxis tick={{ fontSize: 9 }} stroke="#94a3b8" />
                              <Tooltip 
                                formatter={(value) => [formatRupiah(Number(value)), 'Pendapatan']}
                                contentStyle={{ borderRadius: '12px', fontSize: '11px', border: '1px solid #f1f5f9' }}
                              />
                              <Bar dataKey="Pendapatan" fill="#4f46e5" radius={[6, 6, 0, 0]} maxBarSize={35}>
                                {propertyRevenueData.map((entry, index) => (
                                  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                ))}
                              </Bar>
                            </BarChart>
                          </ResponsiveContainer>
                        </div>
                      ) : (
                        <div className="h-64 flex flex-col items-center justify-center text-gray-400 italic text-xs">
                          <Building className="h-10 w-10 text-gray-300 mb-2" />
                          <span>Belum ada properti terdaftar</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* 2. OCCUPANCY CHARTS VIEW */}
                {chartMode === 'occupancy' && (
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {/* Pie Chart Occupancy */}
                    <div className="space-y-4 flex flex-col justify-between">
                      <span className="text-xs font-bold text-gray-800 uppercase tracking-wide">Rasio & Status Keterisian Kamar</span>
                      
                      {totalMyRooms > 0 ? (
                        <div className="flex flex-col md:flex-row items-center justify-center gap-6 py-4">
                          <div className="h-48 w-48 relative flex items-center justify-center shrink-0">
                            <ResponsiveContainer width="100%" height="100%">
                              <PieChart>
                                <Pie
                                  data={occupancyData}
                                  cx="50%"
                                  cy="50%"
                                  innerRadius={55}
                                  outerRadius={75}
                                  paddingAngle={4}
                                  dataKey="value"
                                >
                                  {occupancyData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={entry.color} />
                                  ))}
                                </Pie>
                                <Tooltip formatter={(value) => [`${value} Kamar`, 'Jumlah']} />
                              </PieChart>
                            </ResponsiveContainer>
                            <div className="absolute flex flex-col items-center text-center">
                              <span className="text-2xl font-black text-gray-800 leading-none">{occupancyPercentage}%</span>
                              <span className="text-[8px] text-gray-400 uppercase font-extrabold mt-1">Okupansi</span>
                            </div>
                          </div>

                          <div className="space-y-3 flex-grow max-w-xs text-xs">
                            <div className="bg-rose-50/50 p-2.5 rounded-xl border border-rose-100/50 flex items-center justify-between">
                              <div className="flex items-center space-x-2">
                                <span className="h-2.5 w-2.5 rounded-full bg-rose-500 shrink-0" />
                                <span className="font-semibold text-gray-700">Terisi (Occupied)</span>
                              </div>
                              <span className="font-extrabold text-rose-700">{occupiedCount} Kamar</span>
                            </div>
                            <div className="bg-emerald-50/50 p-2.5 rounded-xl border border-emerald-100/50 flex items-center justify-between">
                              <div className="flex items-center space-x-2">
                                <span className="h-2.5 w-2.5 rounded-full bg-emerald-500 shrink-0" />
                                <span className="font-semibold text-gray-700">Tersedia (Available)</span>
                              </div>
                              <span className="font-extrabold text-emerald-700">{availableCount} Kamar</span>
                            </div>
                            <div className="text-center md:text-left text-[10px] text-gray-400 font-semibold leading-relaxed">
                              Total Kapasitas: {totalMyRooms} Kamar dari properti kelolaan aktif Anda.
                            </div>
                          </div>
                        </div>
                      ) : (
                        <div className="h-64 flex flex-col items-center justify-center text-gray-400 italic text-xs">
                          <Bed className="h-10 w-10 text-gray-300 mb-2" />
                          <span>Belum ada data kamar terdaftar</span>
                        </div>
                      )}
                    </div>

                    {/* Room Type Distribution */}
                    <div className="space-y-4">
                      <span className="text-xs font-bold text-gray-800 uppercase tracking-wide">Analisis Jenis / Tipe Kamar & Unit</span>
                      {roomTypeData.length > 0 ? (
                        <div className="h-64 w-full">
                          <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={roomTypeData} layout="vertical" margin={{ top: 10, right: 10, left: 20, bottom: 0 }}>
                              <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#f1f5f9" />
                              <XAxis type="number" tick={{ fontSize: 9 }} stroke="#94a3b8" />
                              <YAxis dataKey="name" type="category" tick={{ fontSize: 9 }} stroke="#94a3b8" width={75} />
                              <Tooltip contentStyle={{ borderRadius: '12px', fontSize: '11px' }} />
                              <Bar dataKey="Jumlah Unit" fill="#8b5cf6" radius={[0, 6, 6, 0]} maxBarSize={24} />
                            </BarChart>
                          </ResponsiveContainer>
                        </div>
                      ) : (
                        <div className="h-64 flex flex-col items-center justify-center text-gray-400 italic text-xs">
                          <span>Tidak ada detail tipe kamar terdaftar</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* 3. BUSINESS TYPE SEGMENTATION VIEW */}
                {chartMode === 'business-type' && (
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {/* Transaction Type revenue percentage */}
                    <div className="space-y-4">
                      <span className="text-xs font-bold text-gray-800 uppercase tracking-wide">Porsi Pendapatan Berdasarkan Jenis Layanan</span>
                      {businessTypeData.length > 0 ? (
                        <div className="flex flex-col md:flex-row items-center justify-center gap-6 py-4">
                          <div className="h-44 w-44 shrink-0">
                            <ResponsiveContainer width="100%" height="100%">
                              <PieChart>
                                <Pie
                                  data={businessTypeData}
                                  cx="50%"
                                  cy="50%"
                                  outerRadius={70}
                                  dataKey="value"
                                >
                                  {businessTypeData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={entry.color} />
                                  ))}
                                </Pie>
                                <Tooltip formatter={(value) => [formatRupiah(Number(value)), 'Kontribusi']} />
                              </PieChart>
                            </ResponsiveContainer>
                          </div>
                          <div className="space-y-2 flex-grow max-w-xs text-xs">
                            {businessTypeData.map((item, index) => {
                              const share = myRevenue > 0 ? Math.round((item.value / myRevenue) * 100) : 0;
                              return (
                                <div key={index} className="flex items-center justify-between p-2 rounded-lg bg-gray-50 border border-gray-100">
                                  <div className="flex items-center space-x-2">
                                    <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ backgroundColor: item.color }} />
                                    <span className="font-semibold text-gray-700">{item.name}</span>
                                  </div>
                                  <span className="font-extrabold text-gray-900">{share}%</span>
                                </div>
                              );
                            })}
                          </div>
                        </div>
                      ) : (
                        <div className="h-64 flex flex-col items-center justify-center text-gray-400 italic text-xs">
                          <span>Belum ada transaksi tervalidasi</span>
                        </div>
                      )}
                    </div>

                    {/* Transaction Status count */}
                    <div className="space-y-4">
                      <span className="text-xs font-bold text-gray-800 uppercase tracking-wide">Rasio Status Pembayaran Transaksi</span>
                      {statusData.length > 0 ? (
                        <div className="flex flex-col md:flex-row items-center justify-center gap-6 py-4">
                          <div className="h-44 w-44 shrink-0">
                            <ResponsiveContainer width="100%" height="100%">
                              <PieChart>
                                <Pie
                                  data={statusData}
                                  cx="50%"
                                  cy="50%"
                                  outerRadius={70}
                                  innerRadius={45}
                                  dataKey="value"
                                >
                                  {statusData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={entry.color} />
                                  ))}
                                </Pie>
                                <Tooltip formatter={(value) => [`${value} Transaksi`, 'Jumlah']} />
                              </PieChart>
                            </ResponsiveContainer>
                          </div>
                          <div className="space-y-2 flex-grow max-w-xs text-xs">
                            {statusData.map((item, index) => (
                              <div key={index} className="flex items-center justify-between p-2 rounded-lg bg-gray-50 border border-gray-100">
                                <div className="flex items-center space-x-2">
                                  <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ backgroundColor: item.color }} />
                                  <span className="font-semibold text-gray-700">{item.name}</span>
                                </div>
                                <span className="font-extrabold text-gray-900">{item.value} Item</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      ) : (
                        <div className="h-64 flex flex-col items-center justify-center text-gray-400 italic text-xs">
                          <span>Belum ada riwayat status pemesanan</span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 
              ========================================================================
              LEADERBOARD AND ACTIVITY FEED (BENTO GRID DESIGN)
              ========================================================================
            */}
            <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
              
              {/* Leaderboard: Properti Terlaris (Share of Revenue) */}
              <div className="lg:col-span-3 bg-white rounded-2xl border border-gray-100 shadow-xs p-5 md:p-6 space-y-4 flex flex-col justify-between">
                <div>
                  <div className="flex items-center justify-between">
                    <h3 className="font-sans font-black text-sm md:text-base text-gray-900 flex items-center gap-2">
                      <Award className="h-5 w-5 text-amber-500" />
                      <span>Properti Pendapatan Tertinggi</span>
                    </h3>
                    <span className="text-[10px] bg-amber-50 text-amber-800 px-2 py-0.5 rounded-md font-bold">Top Performance</span>
                  </div>
                  <p className="text-[11px] text-gray-400 mt-1">Peringkat kontribusi nilai omset riil dari masing-masing unit properti yang dipasarkan.</p>
                </div>

                <div className="space-y-4 mt-2 flex-grow">
                  {propertyRevenueData.slice(0, 5).map((prop, idx) => {
                    const sharePercentage = myRevenue > 0 ? Math.round((prop['Pendapatan'] / myRevenue) * 100) : 0;
                    return (
                      <div key={idx} className="space-y-1.5">
                        <div className="flex justify-between items-center text-xs">
                          <div className="flex items-center space-x-2 min-w-0">
                            <span className="font-mono font-black text-gray-300 text-sm w-4">0{idx + 1}</span>
                            <span className="font-bold text-gray-800 truncate" title={prop.fullName}>{prop.fullName}</span>
                          </div>
                          <div className="text-right shrink-0">
                            <span className="font-extrabold text-gray-900 block">{formatRupiah(prop['Pendapatan'])}</span>
                            <span className="text-[10px] text-gray-400 block">{prop['Transaksi']} transaksi sukses</span>
                          </div>
                        </div>
                        {/* Progress Bar Gauge */}
                        <div className="w-full bg-gray-100 h-2 rounded-full overflow-hidden">
                          <div 
                            className="bg-gradient-to-r from-blue-500 to-indigo-600 h-full rounded-full transition-all duration-500" 
                            style={{ width: `${sharePercentage}%` }}
                          />
                        </div>
                      </div>
                    );
                  })}

                  {myProperties.length === 0 && (
                    <div className="py-12 text-center text-gray-400 italic text-xs">
                      Belum ada properti terdaftar. Buat properti baru di tab listing.
                    </div>
                  )}
                </div>

                <div className="pt-3 border-t border-gray-50 text-[10px] text-gray-400 text-center font-medium">
                  Menampilkan 5 unit properti dengan performa finansial terbaik.
                </div>
              </div>

              {/* Recent Activity: Transaksi Terbaru */}
              <div className="lg:col-span-2 bg-white rounded-2xl border border-gray-100 shadow-xs p-5 md:p-6 space-y-4 flex flex-col h-full">
                <div>
                  <h3 className="font-sans font-bold text-sm md:text-base text-gray-900 flex items-center gap-2">
                    <Clock className="h-5 w-5 text-blue-600 animate-pulse" />
                    <span>Aktivitas Transaksi Terbaru</span>
                  </h3>
                  <p className="text-[11px] text-gray-400 mt-1">Simulasi log pemesanan dan pembayaran dana masuk dari buyer.</p>
                </div>

                <div className="space-y-3 overflow-y-auto max-h-[360px] flex-grow pr-1">
                  {myTransactions.slice(0, 8).map((tx) => (
                    <div key={tx.id} className="p-3.5 bg-gray-50 rounded-xl border border-gray-100 text-xs flex flex-col space-y-2 hover:bg-gray-100/50 transition-colors">
                      <div className="flex justify-between items-center gap-2">
                        <span className="font-bold text-gray-800 truncate line-clamp-1 flex-1">{tx.propertyName}</span>
                        <span className={`px-2 py-0.5 text-[9px] font-extrabold rounded-md uppercase shrink-0 ${
                          tx.status === 'paid' ? 'bg-emerald-100 text-emerald-800' :
                          tx.status === 'pending' ? 'bg-amber-100 text-amber-800' :
                          'bg-rose-100 text-rose-800'
                        }`}>
                          {tx.status === 'paid' ? 'Paid' : tx.status === 'pending' ? 'Pending' : 'Cancelled'}
                        </span>
                      </div>
                      
                      <div className="flex justify-between text-gray-500 text-[11px]">
                        <span>Buyer: <strong className="text-gray-700">{tx.buyerName}</strong></span>
                        <span className="font-black text-gray-900">{formatRupiah(tx.totalPrice)}</span>
                      </div>

                      <div className="flex justify-between items-center text-[9px] text-gray-400">
                        <span className="font-mono">{tx.createdAt.split('T')[0]}</span>
                        <span className="capitalize font-bold text-blue-600">{tx.type}</span>
                      </div>
                    </div>
                  ))}

                  {myTransactions.length === 0 && (
                    <div className="py-12 text-center text-gray-400 italic text-xs">Belum ada transaksi pemesanan masuk.</div>
                  )}
                </div>
              </div>

            </div>
          </div>
        )}

        {subTab === 'properties' && (
          <PropertyCrudPanel
            properties={properties}
            currentUser={currentUser}
            onRefresh={onRefreshAll}
          />
        )}

        {subTab === 'rooms' && (
          <RoomCrudPanel
            rooms={rooms}
            properties={properties}
            currentUser={currentUser}
            onRefresh={onRefreshAll}
          />
        )}

        {subTab === 'status-grid' && (
          <RoomStatusGrid
            rooms={rooms}
            properties={properties}
            currentUser={currentUser}
            onRefresh={onRefreshAll}
          />
        )}

        {subTab === 'calendar' && (
          <OccupancyCalendar
            rooms={rooms}
            properties={properties}
            transactions={transactions}
            currentUser={currentUser}
          />
        )}
      </div>
    </div>
  );
}
