import React, { useState, useEffect } from 'react';
import { DashboardStats, Factory, JobPost, JobApplication, Notification, User, NeedOrderPost, AdSpaceVideo } from '../types';
import { 
  Building2, 
  Briefcase, 
  Sparkles, 
  Layers, 
  PlusCircle, 
  CheckCircle, 
  Clock, 
  ArrowRight, 
  TrendingUp, 
  Star,
  Users,
  Megaphone,
  ShoppingBag,
  Target,
  Film
} from 'lucide-react';

export interface UserDashboardProps {
  user: User | null;
  stats: DashboardStats;
  factories: Factory[];
  jobs: JobPost[];
  applications: JobApplication[];
  notifications: Notification[];
  needOrders?: NeedOrderPost[];
  myNeedOrders?: NeedOrderPost[];
  setActiveTab: (tab: string) => void;
}

export default function UserDashboard({
  user,
  stats,
  factories,
  jobs,
  applications,
  notifications,
  needOrders = [],
  myNeedOrders = [],
  setActiveTab
}: UserDashboardProps) {
  // Real-time ACI Video Ads State
  const [adSpaceVideos, setAdSpaceVideos] = useState<AdSpaceVideo[]>([]);

  useEffect(() => {
    fetch('/api/aci/ads')
      .then(res => res.ok ? res.json() : [])
      .then(data => {
        if (Array.isArray(data)) {
          setAdSpaceVideos(data);
        }
      })
      .catch(err => console.error('Error loading ad space videos:', err));
  }, []);

  const spot1Ad = adSpaceVideos.find(a => a.spotNumber === 1 && a.isActive);
  const spot2Ad = adSpaceVideos.find(a => a.spotNumber === 2 && a.isActive);

  // Filter user specific data
  const userFactories = factories.filter(f => f.userId === user?.id || user?.role === 'Admin');
  const approvedUserFactories = userFactories.filter(f => f.status === 'Approved' || !f.status);

  // Automated Dynamic Rating Logic based directly on Order Received and Shipment performance metrics
  const getDynamicFactoryRating = (f: Factory): number => {
    // 1. Orders received via Job Applications / Bids for this factory
    const factoryApps = applications.filter(a => 
      a.factoryId === f.id || 
      (a.factoryName && f.name && a.factoryName.trim().toLowerCase() === f.name.trim().toLowerCase())
    );
    const ordersReceivedFromBids = factoryApps.length;
    // Shipments executed / completed (Approved bids/applications)
    const shipmentsExecutedFromBids = factoryApps.filter(a => a.status === 'Approved').length;

    // 2. Capacity quotes in Need Orders for this factory's user
    let quotesReceived = 0;
    let quotesApproved = 0;
    needOrders.forEach(no => {
      if (no.quotes) {
        no.quotes.forEach(q => {
          if (q.userId === f.userId) {
            quotesReceived++;
            if (q.status === 'Approved') quotesApproved++;
          }
        });
      }
    });

    const totalOrdersReceived = ordersReceivedFromBids + quotesReceived;
    const totalShipments = shipmentsExecutedFromBids + quotesApproved;

    if (totalOrdersReceived === 0 || totalShipments === 0) {
      return 0.0;
    }

    // Performance Ratio = Shipments Executed / Orders Received
    const performanceRatio = Math.min(1, totalShipments / totalOrdersReceived);
    // Scale score dynamically between 0.0 and 5.0 based on shipment completion
    const score = performanceRatio * 5.0;
    return Number(score.toFixed(1));
  };

  // Average rating calculation for user's approved factories
  const avgRatingVal = approvedUserFactories.length > 0
    ? (approvedUserFactories.reduce((sum, f) => sum + getDynamicFactoryRating(f), 0) / approvedUserFactories.length).toFixed(1)
    : (userFactories.length > 0 
        ? (userFactories.reduce((sum, f) => sum + getDynamicFactoryRating(f), 0) / userFactories.length).toFixed(1) 
        : '0.0');

  // User posted orders (Jobs/RFQs)
  const userJobs = jobs.filter(j => j.userId === user?.id);
  const acceptedUserJobs = userJobs.filter(j => 
    j.status === 'Closed' || 
    j.status === 'Filled' || 
    j.isProceed || 
    (j.bids && j.bids.some(b => b.status === 'Approved'))
  );
  const ordersAcceptancePct = userJobs.length > 0 
    ? Math.round((acceptedUserJobs.length / userJobs.length) * 100) 
    : 0;

  // User posted "Need Orders"
  const userNeedOrders = (myNeedOrders.length > 0 ? myNeedOrders : needOrders).filter(n => n.userId === user?.id);
  const acceptedNeedOrders = userNeedOrders.filter(n => 
    n.isClosed || 
    n.isProceed || 
    n.proceed_status === 'Approved' || 
    (n.quotes && n.quotes.some(q => q.status === 'Approved'))
  );
  const needOrdersAcceptancePct = userNeedOrders.length > 0 
    ? Math.round((acceptedNeedOrders.length / userNeedOrders.length) * 100) 
    : 0;

  // Existing match success rate logic
  const userApplications = applications.filter(a => a.userId === user?.id || userFactories.some(f => f.name === a.factoryName));
  const approvedContracts = userApplications.filter(a => a.status === 'Approved');
  const matchSuccessRateText = applications.length > 0 
    ? `${Math.round((approvedContracts.length / applications.length) * 100)}%` 
    : '98%';

  // Platform wide totals (Reset initial fallback values to 0)
  const platformUsersCount = stats.totalUsersCount ?? 0;
  const platformFactoriesCount = stats.totalFactoriesCount ?? factories.length ?? 0;
  const platformJobsCount = stats.totalJobsCount ?? jobs.length ?? 0;
  const platformNeedOrdersCount = stats.totalNeedOrdersCount ?? needOrders.length ?? 0;

  return (
    <div className="space-y-8">
      {/* User Hero Welcome Banner */}
      <div className="bg-gradient-to-r from-slate-900 via-slate-800 to-blue-950 rounded-2xl p-6 text-white shadow-lg border border-slate-700/60 flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div className="space-y-2">
          <div className="flex items-center space-x-2 bg-blue-500/10 text-blue-400 px-3 py-1 rounded-full text-xs font-mono w-fit border border-blue-500/20">
            <Sparkles className="w-3.5 h-3.5" />
            <span>Garment B2B Workspace</span>
          </div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight">
            Welcome back, {user?.name || 'Partner'}!
          </h1>
          <p className="text-slate-300 text-sm max-w-xl">
            Manage your factory portfolio, post new apparel sourcing requirements, track submitted bids, and execute contracts effortlessly.
          </p>
        </div>
        <div className="flex flex-wrap gap-3">
          <button 
            onClick={() => setActiveTab('factories')}
            className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold px-4 py-2.5 rounded-xl shadow transition duration-200 flex items-center space-x-2 cursor-pointer"
          >
            <Building2 className="w-4 h-4" />
            <span>My Factories</span>
          </button>
          <button 
            onClick={() => setActiveTab('jobs')}
            className="bg-slate-800 hover:bg-slate-700 text-white text-xs font-semibold px-4 py-2.5 rounded-xl shadow border border-slate-700 transition duration-200 flex items-center space-x-2 cursor-pointer"
          >
            <Briefcase className="w-4 h-4" />
            <span>Order Feed</span>
          </button>
        </div>
      </div>

      {/* TOP ROW / SUMMARY CARDS */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        {/* 1. My Factories */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition">
          <div className="flex justify-between items-start">
            <div className="space-y-1">
              <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">My Factories</span>
              <p className="text-3xl font-bold text-slate-900">{approvedUserFactories.length}</p>
            </div>
            <div className="bg-blue-50 p-2.5 rounded-xl text-blue-600">
              <Building2 className="w-6 h-6" />
            </div>
          </div>
          <div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
            <span className="text-amber-600 font-semibold flex items-center">
              <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-500 mr-1" />
              Avg Rating: {avgRatingVal} / 5.0
            </span>
            <button onClick={() => setActiveTab('factories')} className="text-blue-600 font-semibold hover:underline">
              View All &rarr;
            </button>
          </div>
        </div>

        {/* 2. Orders */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition">
          <div className="flex justify-between items-start">
            <div className="space-y-1">
              <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Orders</span>
              <p className="text-3xl font-bold text-slate-900">{userJobs.length}</p>
            </div>
            <div className="bg-orange-50 p-2.5 rounded-xl text-orange-600">
              <Briefcase className="w-6 h-6" />
            </div>
          </div>
          <div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
            <span className="text-slate-600 font-medium">
              Accepted: <span className="font-bold text-slate-800">{acceptedUserJobs.length}</span> ({ordersAcceptancePct}%)
            </span>
            <button onClick={() => setActiveTab('jobs')} className="text-orange-600 font-semibold hover:underline">
              Manage &rarr;
            </button>
          </div>
        </div>

        {/* 3. Our Need Orders */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition">
          <div className="flex justify-between items-start">
            <div className="space-y-1">
              <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Our Need Orders</span>
              <p className="text-3xl font-bold text-slate-900">{userNeedOrders.length}</p>
            </div>
            <div className="bg-purple-50 p-2.5 rounded-xl text-purple-600">
              <Layers className="w-6 h-6" />
            </div>
          </div>
          <div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
            <span className="text-purple-600 font-medium">
              Accepted: <span className="font-bold text-purple-800">{acceptedNeedOrders.length}</span> ({needOrdersAcceptancePct}%)
            </span>
            <button onClick={() => setActiveTab('jobs')} className="text-purple-600 font-semibold hover:underline">
              View &rarr;
            </button>
          </div>
        </div>

        {/* 4. Match Success Rate */}
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition">
          <div className="flex justify-between items-start">
            <div className="space-y-1">
              <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Match Success Rate</span>
              <p className="text-3xl font-bold text-slate-900">{matchSuccessRateText}</p>
            </div>
            <div className="bg-emerald-50 p-2.5 rounded-xl text-emerald-600">
              <TrendingUp className="w-6 h-6" />
            </div>
          </div>
          <div className="mt-4 pt-3 border-t border-slate-100 text-xs text-slate-500">
            High Contract Fulfillment Quality
          </div>
        </div>
      </div>

      {/* MIDDLE SECTION: 5. MY FACTORY PORTFOLIO & 6. AD SPACE */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left 2 Columns: 5. My Factory Portfolio */}
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-slate-900 tracking-tight">My Factory Portfolio</h2>
              <p className="text-sm text-slate-700 mt-1 font-normal">
                Registered manufacturing units with factory-wise quality ratings.
              </p>
            </div>

            <div className="mt-5">
              {/* Header */}
              <div className="flex items-center justify-between pb-2 font-bold text-slate-900 text-sm border-b border-slate-200">
                <span className="w-2/3 sm:w-3/4">Factory</span>
                <span className="w-1/3 sm:w-1/4 text-right sm:text-center pr-2 sm:pr-0">Rating</span>
              </div>

              {/* Rows */}
              <div className="divide-y divide-slate-100">
                {userFactories.length === 0 ? (
                  <div className="py-8 text-center text-xs text-slate-500 font-medium">
                    No factories registered yet
                  </div>
                ) : (
                  userFactories.map((f) => {
                    const rating = getDynamicFactoryRating(f).toFixed(1);
                    return (
                      <div key={f.id} className="flex items-center justify-between py-3.5">
                        <span className="w-2/3 sm:w-3/4 font-semibold text-slate-900 text-sm uppercase tracking-tight pr-4">
                          {f.name}
                        </span>
                        <div className="w-1/3 sm:w-1/4 flex items-center justify-end sm:justify-center space-x-2 text-slate-900 font-semibold text-sm">
                          <svg className="w-5 h-5 text-orange-500 fill-orange-500" viewBox="0 0 24 24">
                            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                          </svg>
                          <span>{rating}</span>
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Right 1 Column: 6. Ad Space (Live Video Ads Sync) */}
        <div className="space-y-6">
          <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-4">
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <div className="flex items-center space-x-2">
                <Megaphone className="w-4 h-4 text-indigo-600" />
                <h2 className="text-sm font-bold text-slate-900 uppercase tracking-wider">Ad Space</h2>
              </div>
              <span className="text-[10px] bg-indigo-50 text-indigo-600 border border-indigo-200 font-semibold px-2 py-0.5 rounded">
                Sponsored Videos
              </span>
            </div>

            <div className="space-y-5">
              {/* Advertisement Spot 1 */}
              {spot1Ad && spot1Ad.videoUrl ? (
                <div className="bg-slate-900 rounded-xl overflow-hidden border border-slate-800 shadow-md space-y-2 p-2">
                  <div className="flex items-center justify-between px-1">
                    <span className="text-[10px] font-bold text-indigo-400 uppercase tracking-wider">Spot 1</span>
                    <span className="text-[9px] text-slate-400 truncate max-w-[150px]">{spot1Ad.title}</span>
                  </div>
                  <div className="aspect-video bg-black rounded-lg overflow-hidden relative">
                    <video 
                      src={spot1Ad.videoUrl} 
                      controls 
                      autoPlay 
                      muted 
                      loop 
                      className="w-full h-full object-cover"
                    />
                  </div>
                  {spot1Ad.caption && (
                    <p className="text-[11px] text-slate-300 font-medium px-1 line-clamp-2">{spot1Ad.caption}</p>
                  )}
                </div>
              ) : (
                <div className="border-2 border-dashed border-slate-200 bg-slate-50/80 rounded-xl p-5 text-center min-h-[140px] flex flex-col items-center justify-center space-y-2">
                  <div className="w-8 h-8 rounded-full bg-slate-200/80 flex items-center justify-center text-slate-400">
                    <Megaphone className="w-4 h-4" />
                  </div>
                  <div>
                    <p className="text-xs font-bold text-slate-600">Advertisement Space 1</p>
                    <p className="text-[10px] text-slate-400">Aci Video Stream Spot 1</p>
                  </div>
                </div>
              )}

              {/* Advertisement Spot 2 */}
              {spot2Ad && spot2Ad.videoUrl ? (
                <div className="bg-slate-900 rounded-xl overflow-hidden border border-slate-800 shadow-md space-y-2 p-2">
                  <div className="flex items-center justify-between px-1">
                    <span className="text-[10px] font-bold text-purple-400 uppercase tracking-wider">Spot 2</span>
                    <span className="text-[9px] text-slate-400 truncate max-w-[150px]">{spot2Ad.title}</span>
                  </div>
                  <div className="aspect-video bg-black rounded-lg overflow-hidden relative">
                    <video 
                      src={spot2Ad.videoUrl} 
                      controls 
                      autoPlay 
                      muted 
                      loop 
                      className="w-full h-full object-cover"
                    />
                  </div>
                  {spot2Ad.caption && (
                    <p className="text-[11px] text-slate-300 font-medium px-1 line-clamp-2">{spot2Ad.caption}</p>
                  )}
                </div>
              ) : (
                <div className="border-2 border-dashed border-slate-200 bg-slate-50/80 rounded-xl p-5 text-center min-h-[140px] flex flex-col items-center justify-center space-y-2">
                  <div className="w-8 h-8 rounded-full bg-slate-200/80 flex items-center justify-center text-slate-400">
                    <Megaphone className="w-4 h-4" />
                  </div>
                  <div>
                    <p className="text-xs font-bold text-slate-600">Advertisement Space 2</p>
                    <p className="text-[10px] text-slate-400">Aci Video Stream Spot 2</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* BOTTOM ROW / PLATFORM-WIDE STATISTICS */}
      <div>
        <div className="mb-4 flex items-center space-x-2">
          <div className="h-4 w-1 bg-blue-600 rounded-full" />
          <h2 className="text-base font-bold text-slate-900">Platform-Wide Statistics</h2>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
          {/* 7. Users */}
          <div className="bg-slate-900 text-white p-5 rounded-2xl border border-slate-800 shadow-md">
            <div className="flex justify-between items-start">
              <div className="space-y-1">
                <span className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Users</span>
                <p className="text-3xl font-bold text-white">{platformUsersCount}</p>
              </div>
              <div className="bg-blue-500/20 p-2.5 rounded-xl text-blue-400 border border-blue-500/30">
                <Users className="w-6 h-6" />
              </div>
            </div>
            <p className="text-[11px] text-slate-400 mt-3">Registered Platform Members</p>
          </div>

          {/* 8. Factories */}
          <div className="bg-slate-900 text-white p-5 rounded-2xl border border-slate-800 shadow-md">
            <div className="flex justify-between items-start">
              <div className="space-y-1">
                <span className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Factories</span>
                <p className="text-3xl font-bold text-white">{platformFactoriesCount}</p>
              </div>
              <div className="bg-emerald-500/20 p-2.5 rounded-xl text-emerald-400 border border-emerald-500/30">
                <Building2 className="w-6 h-6" />
              </div>
            </div>
            <p className="text-[11px] text-slate-400 mt-3">Registered Manufacturing Units</p>
          </div>

          {/* 9. Orders */}
          <div className="bg-slate-900 text-white p-5 rounded-2xl border border-slate-800 shadow-md">
            <div className="flex justify-between items-start">
              <div className="space-y-1">
                <span className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Orders</span>
                <p className="text-3xl font-bold text-white">{platformJobsCount}</p>
              </div>
              <div className="bg-orange-500/20 p-2.5 rounded-xl text-orange-400 border border-orange-500/30">
                <ShoppingBag className="w-6 h-6" />
              </div>
            </div>
            <p className="text-[11px] text-slate-400 mt-3">Total Posted Marketplace Orders</p>
          </div>

          {/* 10. Our Need Orders */}
          <div className="bg-slate-900 text-white p-5 rounded-2xl border border-slate-800 shadow-md">
            <div className="flex justify-between items-start">
              <div className="space-y-1">
                <span className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Our Need Orders</span>
                <p className="text-3xl font-bold text-white">{platformNeedOrdersCount}</p>
              </div>
              <div className="bg-purple-500/20 p-2.5 rounded-xl text-purple-400 border border-purple-500/30">
                <Target className="w-6 h-6" />
              </div>
            </div>
            <p className="text-[11px] text-slate-400 mt-3">Total Capacity & Sourcing Posts</p>
          </div>
        </div>
      </div>
    </div>
  );
}

