'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { getCommissionSummary, getCommissionRules } from '@/services/commission/commission.service';
import { CommissionSummary, CommissionRule } from '@/types/commission.types';

export default function AdminCommissionManagementPage() {
  const router = useRouter();
  const [summary, setSummary] = useState<CommissionSummary | null>(null);
  const [rules, setRules] = useState<CommissionRule[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        const [summaryData, rulesData] = await Promise.all([
          getCommissionSummary(),
          getCommissionRules(),
        ]);
        setSummary(summaryData);
        setRules(rulesData);
      } catch (err) {
        console.error('Failed to fetch commission data:', err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, []);

  const quickLinks = [
    {
      title: 'Commission History',
      description: 'View all commission transactions across the platform',
      href: '/admin/commission-management/history',
      icon: (
        <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
        </svg>
      ),
      color: 'bg-blue-500',
    },
    {
      title: 'Commission Reports',
      description: 'Generate and export detailed commission reports',
      href: '/admin/commission-management/reports',
      icon: (
        <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
      ),
      color: 'bg-green-500',
    },
    {
      title: 'Commission Settings',
      description: 'Manage commission rules, manual credits, and reversals',
      href: '/admin/commission-management/settings',
      icon: (
        <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      ),
      color: 'bg-purple-500',
    },
    {
      title: 'Commission Analytics',
      description: 'Analyze commission trends, distributions, and top users',
      href: '/admin/commission-management/analytics',
      icon: (
        <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z" />
        </svg>
      ),
      color: 'bg-orange-500',
    },
  ];

  const statCards = summary
    ? [
        { label: 'Total Commissions', value: summary.totalCommissions, color: 'text-blue-600' },
        { label: 'Total Amount', value: `$${summary.totalAmount.toFixed(2)}`, color: 'text-green-600' },
        { label: 'Paid', value: `$${summary.paidAmount.toFixed(2)}`, color: 'text-green-600' },
        { label: 'Pending', value: `$${summary.pendingAmount.toFixed(2)}`, color: 'text-yellow-600' },
      ]
    : [];

  return (
    <div className="container mx-auto p-4 space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Commission Management</h1>
        <p className="mt-1 text-sm text-gray-500">
          Manage commissions, rules, reports, and analytics for the platform.
        </p>
      </div>

      {/* Quick Stats */}
      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="bg-white rounded-lg shadow p-6 animate-pulse">
              <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
              <div className="h-8 bg-gray-200 rounded w-3/4"></div>
            </div>
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {statCards.map((card, index) => (
            <div key={index} className="bg-white rounded-lg shadow p-6">
              <p className="text-sm font-medium text-gray-500">{card.label}</p>
              <p className={`mt-2 text-3xl font-bold ${card.color}`}>{card.value}</p>
            </div>
          ))}
        </div>
      )}

      {/* Active Rules Summary */}
      <div className="bg-white rounded-lg shadow p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Active Commission Rules</h2>
        {isLoading ? (
          <div className="animate-pulse space-y-2">
            {[...Array(3)].map((_, i) => (
              <div key={i} className="h-6 bg-gray-200 rounded w-full"></div>
            ))}
          </div>
        ) : rules.length > 0 ? (
          <div className="space-y-2">
            {rules.filter((r) => r.isActive).map((rule) => (
              <div key={rule.id} className="flex items-center justify-between py-2 border-b last:border-0">
                <div className="flex items-center">
                  <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 mr-2">
                    {rule.type}
                  </span>
                  <span className="text-sm text-gray-500">{rule.description}</span>
                </div>
                <span className="text-sm font-medium text-gray-900">{rule.percentage}%</span>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-gray-500">No active commission rules configured.</p>
        )}
        <div className="mt-4">
          <button
            onClick={() => router.push('/admin/commission-management/settings')}
            className="text-sm text-indigo-600 hover:text-indigo-500 font-medium"
          >
            Manage Rules →
          </button>
        </div>
      </div>

      {/* Quick Links */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {quickLinks.map((link) => (
          <button
            key={link.title}
            onClick={() => router.push(link.href)}
            className="bg-white rounded-lg shadow p-6 text-left hover:shadow-md transition-shadow duration-200"
          >
            <div className={`inline-flex items-center justify-center p-2 rounded-lg text-white ${link.color}`}>
              {link.icon}
            </div>
            <h3 className="mt-4 text-lg font-semibold text-gray-900">{link.title}</h3>
            <p className="mt-1 text-sm text-gray-500">{link.description}</p>
          </button>
        ))}
      </div>
    </div>
  );
}
