/**
 * Seller Dashboard Page
 * Dashboard for product creators to manage their listings and track sales
 */

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Plus,
  Package,
  DollarSign,
  Users,
  TrendingUp,
  BarChart2,
  Eye,
  Edit,
  Trash2,
  MoreVertical,
  Star,
  Clock,
  ChevronRight,
  ArrowUpRight,
  ArrowDownRight,
  Loader2,
  AlertCircle,
  Filter,
} from 'lucide-react';

// ============================================================================
// Types
// ============================================================================

interface SellerProduct {
  id: string;
  name: string;
  type: 'signals' | 'courses' | 'advisory';
  status: 'active' | 'draft' | 'inactive';
  price: number;
  subscribers: number;
  rating: number;
  reviews: number;
  revenue: number;
  views: number;
  createdAt: string;
  thumbnailUrl?: string;
}

interface SellerStats {
  totalRevenue: number;
  revenueChange: number;
  totalSubscribers: number;
  subscribersChange: number;
  activeProducts: number;
  averageRating: number;
  pendingPayouts: number;
  nextPayoutDate: string;
}

interface SalesData {
  date: string;
  revenue: number;
  subscribers: number;
}

// ============================================================================
// Mock Data (replace with API calls)
// ============================================================================

const MOCK_STATS: SellerStats = {
  totalRevenue: 12450.00,
  revenueChange: 15.3,
  totalSubscribers: 342,
  subscribersChange: 8.2,
  activeProducts: 5,
  averageRating: 4.7,
  pendingPayouts: 2340.00,
  nextPayoutDate: '2026-02-15',
};

const MOCK_PRODUCTS: SellerProduct[] = [
  {
    id: '1',
    name: 'Pro Trading Signals',
    type: 'signals',
    status: 'active',
    price: 49.99,
    subscribers: 156,
    rating: 4.8,
    reviews: 42,
    revenue: 7798.44,
    views: 2340,
    createdAt: '2025-10-15',
  },
  {
    id: '2',
    name: 'Forex Masterclass',
    type: 'courses',
    status: 'active',
    price: 199.00,
    subscribers: 89,
    rating: 4.6,
    reviews: 28,
    revenue: 3982.11,
    views: 1890,
    createdAt: '2025-11-20',
  },
  {
    id: '3',
    name: '1-on-1 Trading Coaching',
    type: 'advisory',
    status: 'active',
    price: 150.00,
    subscribers: 12,
    rating: 5.0,
    reviews: 8,
    revenue: 1800.00,
    views: 456,
    createdAt: '2025-12-01',
  },
  {
    id: '4',
    name: 'Crypto Signals (Beta)',
    type: 'signals',
    status: 'draft',
    price: 39.99,
    subscribers: 0,
    rating: 0,
    reviews: 0,
    revenue: 0,
    views: 0,
    createdAt: '2026-01-28',
  },
];

// ============================================================================
// Stats Card Component
// ============================================================================

interface StatsCardProps {
  title: string;
  value: string | number;
  change?: number;
  icon: React.ReactNode;
  iconBg: string;
  prefix?: string;
  suffix?: string;
}

const StatsCard: React.FC<StatsCardProps> = ({
  title,
  value,
  change,
  icon,
  iconBg,
  prefix,
  suffix,
}) => (
  <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
    <div className="flex items-start justify-between mb-4">
      <div className={`w-12 h-12 rounded-lg ${iconBg} flex items-center justify-center`}>
        {icon}
      </div>
      {change !== undefined && (
        <div
          className={`flex items-center gap-1 text-sm ${
            change >= 0 ? 'text-green-400' : 'text-red-400'
          }`}
        >
          {change >= 0 ? (
            <ArrowUpRight className="w-4 h-4" />
          ) : (
            <ArrowDownRight className="w-4 h-4" />
          )}
          {Math.abs(change)}%
        </div>
      )}
    </div>
    <p className="text-2xl font-bold text-white">
      {prefix}
      {typeof value === 'number' ? value.toLocaleString() : value}
      {suffix}
    </p>
    <p className="text-sm text-gray-400 mt-1">{title}</p>
  </div>
);

// ============================================================================
// Product Row Component
// ============================================================================

interface ProductRowProps {
  product: SellerProduct;
  onEdit: (id: string) => void;
  onDelete: (id: string) => void;
  onView: (id: string) => void;
}

const ProductRow: React.FC<ProductRowProps> = ({ product, onEdit, onDelete, onView }) => {
  const [showMenu, setShowMenu] = useState(false);

  const statusColors = {
    active: 'bg-green-500/20 text-green-400',
    draft: 'bg-yellow-500/20 text-yellow-400',
    inactive: 'bg-gray-500/20 text-gray-400',
  };

  const typeIcons = {
    signals: '📊',
    courses: '📚',
    advisory: '👨‍💼',
  };

  return (
    <tr className="border-b border-gray-700 hover:bg-gray-800/50">
      <td className="px-4 py-4">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-lg bg-gray-700 flex items-center justify-center text-lg flex-shrink-0">
            {typeIcons[product.type]}
          </div>
          <div className="min-w-0">
            <p className="font-medium text-white truncate">{product.name}</p>
            <p className="text-sm text-gray-500 capitalize">{product.type}</p>
          </div>
        </div>
      </td>
      <td className="px-4 py-4">
        <span
          className={`px-2.5 py-1 rounded-full text-xs font-medium capitalize ${
            statusColors[product.status]
          }`}
        >
          {product.status}
        </span>
      </td>
      <td className="px-4 py-4 text-white">${product.price.toFixed(2)}</td>
      <td className="px-4 py-4 text-white">{product.subscribers}</td>
      <td className="px-4 py-4">
        {product.rating > 0 ? (
          <div className="flex items-center gap-1">
            <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
            <span className="text-white">{product.rating.toFixed(1)}</span>
            <span className="text-gray-500 text-sm">({product.reviews})</span>
          </div>
        ) : (
          <span className="text-gray-500">No reviews</span>
        )}
      </td>
      <td className="px-4 py-4 text-green-400 font-medium">
        ${product.revenue.toLocaleString()}
      </td>
      <td className="px-4 py-4">
        <div className="relative">
          <button
            onClick={() => setShowMenu(!showMenu)}
            className="p-2 text-gray-400 hover:text-white rounded-lg hover:bg-gray-700 transition-colors"
          >
            <MoreVertical className="w-4 h-4" />
          </button>

          {showMenu && (
            <>
              <div
                className="fixed inset-0 z-10"
                onClick={() => setShowMenu(false)}
              />
              <div className="absolute right-0 mt-1 w-40 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-20">
                <button
                  onClick={() => {
                    onView(product.id);
                    setShowMenu(false);
                  }}
                  className="w-full px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700 flex items-center gap-2"
                >
                  <Eye className="w-4 h-4" />
                  View
                </button>
                <button
                  onClick={() => {
                    onEdit(product.id);
                    setShowMenu(false);
                  }}
                  className="w-full px-4 py-2 text-left text-sm text-gray-300 hover:bg-gray-700 flex items-center gap-2"
                >
                  <Edit className="w-4 h-4" />
                  Edit
                </button>
                <button
                  onClick={() => {
                    onDelete(product.id);
                    setShowMenu(false);
                  }}
                  className="w-full px-4 py-2 text-left text-sm text-red-400 hover:bg-gray-700 flex items-center gap-2"
                >
                  <Trash2 className="w-4 h-4" />
                  Delete
                </button>
              </div>
            </>
          )}
        </div>
      </td>
    </tr>
  );
};

// ============================================================================
// Main Component
// ============================================================================

export default function SellerDashboard() {
  const [stats, setStats] = useState<SellerStats | null>(null);
  const [products, setProducts] = useState<SellerProduct[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'draft' | 'inactive'>('all');
  const [typeFilter, setTypeFilter] = useState<'all' | 'signals' | 'courses' | 'advisory'>('all');

  // Fetch seller data
  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        // Simulated API call - replace with actual service
        await new Promise((resolve) => setTimeout(resolve, 1000));
        setStats(MOCK_STATS);
        setProducts(MOCK_PRODUCTS);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load data');
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  // Filter products
  const filteredProducts = products.filter((product) => {
    if (statusFilter !== 'all' && product.status !== statusFilter) return false;
    if (typeFilter !== 'all' && product.type !== typeFilter) return false;
    return true;
  });

  // Handlers
  const handleEditProduct = (id: string) => {
    console.log('Edit product:', id);
    // Navigate to edit page
  };

  const handleDeleteProduct = (id: string) => {
    if (window.confirm('Are you sure you want to delete this product?')) {
      setProducts(products.filter((p) => p.id !== id));
    }
  };

  const handleViewProduct = (id: string) => {
    const product = products.find((p) => p.id === id);
    if (product) {
      window.open(`/marketplace/${product.type}/${id}`, '_blank');
    }
  };

  // Loading state
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="flex flex-col items-center justify-center min-h-96">
        <AlertCircle className="w-12 h-12 text-red-400 mb-4" />
        <h2 className="text-xl font-semibold text-white mb-2">Failed to Load</h2>
        <p className="text-gray-400">{error}</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Seller Dashboard</h1>
          <p className="text-gray-400">Manage your products and track sales</p>
        </div>
        <Link
          to="/marketplace/seller/create"
          className="inline-flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-500 text-white font-medium rounded-lg transition-colors"
        >
          <Plus className="w-5 h-5" />
          Create Product
        </Link>
      </div>

      {/* Stats Grid */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <StatsCard
            title="Total Revenue"
            value={stats.totalRevenue.toFixed(2)}
            change={stats.revenueChange}
            icon={<DollarSign className="w-6 h-6 text-green-400" />}
            iconBg="bg-green-500/20"
            prefix="$"
          />
          <StatsCard
            title="Total Subscribers"
            value={stats.totalSubscribers}
            change={stats.subscribersChange}
            icon={<Users className="w-6 h-6 text-blue-400" />}
            iconBg="bg-blue-500/20"
          />
          <StatsCard
            title="Active Products"
            value={stats.activeProducts}
            icon={<Package className="w-6 h-6 text-purple-400" />}
            iconBg="bg-purple-500/20"
          />
          <StatsCard
            title="Average Rating"
            value={stats.averageRating.toFixed(1)}
            icon={<Star className="w-6 h-6 text-yellow-400" />}
            iconBg="bg-yellow-500/20"
          />
        </div>
      )}

      {/* Payout Notice */}
      {stats && stats.pendingPayouts > 0 && (
        <div className="bg-gray-800 rounded-xl border border-gray-700 p-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="w-10 h-10 rounded-lg bg-green-500/20 flex items-center justify-center">
              <DollarSign className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="font-medium text-white">
                Pending Payout: ${stats.pendingPayouts.toFixed(2)}
              </p>
              <p className="text-sm text-gray-400">
                Next payout scheduled for{' '}
                {new Date(stats.nextPayoutDate).toLocaleDateString('en-US', {
                  month: 'long',
                  day: 'numeric',
                  year: 'numeric',
                })}
              </p>
            </div>
          </div>
          <Link
            to="/billing"
            className="text-blue-400 hover:text-blue-300 flex items-center gap-1 text-sm"
          >
            View Details
            <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      )}

      {/* Products Table */}
      <div className="bg-gray-800 rounded-xl border border-gray-700">
        {/* Table Header */}
        <div className="p-4 border-b border-gray-700 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <h2 className="text-lg font-semibold text-white">Your Products</h2>
          <div className="flex flex-wrap gap-3">
            {/* Status Filter */}
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-gray-300 text-sm focus:border-blue-500 focus:outline-none"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="draft">Draft</option>
              <option value="inactive">Inactive</option>
            </select>

            {/* Type Filter */}
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value as typeof typeFilter)}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-gray-300 text-sm focus:border-blue-500 focus:outline-none"
            >
              <option value="all">All Types</option>
              <option value="signals">Signals</option>
              <option value="courses">Courses</option>
              <option value="advisory">Advisory</option>
            </select>
          </div>
        </div>

        {/* Table */}
        {filteredProducts.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="text-left text-sm text-gray-400 border-b border-gray-700">
                  <th className="px-4 py-3 font-medium">Product</th>
                  <th className="px-4 py-3 font-medium">Status</th>
                  <th className="px-4 py-3 font-medium">Price</th>
                  <th className="px-4 py-3 font-medium">Subscribers</th>
                  <th className="px-4 py-3 font-medium">Rating</th>
                  <th className="px-4 py-3 font-medium">Revenue</th>
                  <th className="px-4 py-3 font-medium w-12"></th>
                </tr>
              </thead>
              <tbody>
                {filteredProducts.map((product) => (
                  <ProductRow
                    key={product.id}
                    product={product}
                    onEdit={handleEditProduct}
                    onDelete={handleDeleteProduct}
                    onView={handleViewProduct}
                  />
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="p-12 text-center">
            <Package className="w-12 h-12 text-gray-600 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-white mb-2">No products found</h3>
            <p className="text-gray-400 mb-4">
              {products.length === 0
                ? "You haven't created any products yet."
                : 'No products match the selected filters.'}
            </p>
            {products.length === 0 && (
              <Link
                to="/marketplace/seller/create"
                className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg transition-colors"
              >
                <Plus className="w-4 h-4" />
                Create Your First Product
              </Link>
            )}
          </div>
        )}
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Link
          to="/marketplace/seller/create"
          className="bg-gray-800 rounded-xl border border-gray-700 p-6 hover:border-gray-600 transition-colors group"
        >
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-blue-500/20 flex items-center justify-center group-hover:bg-blue-500/30 transition-colors">
              <Plus className="w-6 h-6 text-blue-400" />
            </div>
            <div>
              <h3 className="font-medium text-white">Create New Product</h3>
              <p className="text-sm text-gray-400">Add a new listing to marketplace</p>
            </div>
          </div>
        </Link>

        <Link
          to="/billing"
          className="bg-gray-800 rounded-xl border border-gray-700 p-6 hover:border-gray-600 transition-colors group"
        >
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-green-500/20 flex items-center justify-center group-hover:bg-green-500/30 transition-colors">
              <DollarSign className="w-6 h-6 text-green-400" />
            </div>
            <div>
              <h3 className="font-medium text-white">Payout Settings</h3>
              <p className="text-sm text-gray-400">Manage payment methods</p>
            </div>
          </div>
        </Link>

        <Link
          to="/settings"
          className="bg-gray-800 rounded-xl border border-gray-700 p-6 hover:border-gray-600 transition-colors group"
        >
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-lg bg-purple-500/20 flex items-center justify-center group-hover:bg-purple-500/30 transition-colors">
              <BarChart2 className="w-6 h-6 text-purple-400" />
            </div>
            <div>
              <h3 className="font-medium text-white">Analytics</h3>
              <p className="text-sm text-gray-400">View detailed performance</p>
            </div>
          </div>
        </Link>
      </div>
    </div>
  );
}
