'use client';

import { useState } from 'react';
import { useCommissionAnalytics } from '@/hooks/commission/useCommissionAnalytics';

export const CommissionAnalyticsView = () => {
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [granularity, setGranularity] = useState<'day' | 'week' | 'month'>('day');

  const filters = {
    dateFrom: dateFrom || undefined,
    dateTo: dateTo || undefined,
    granularity,
  };

  const { analytics, isLoading, error, refetch } = useCommissionAnalytics(filters);

  return (
    <div className="space-y-6">
      {/* Filters */}
      <div className="bg-white rounded-lg shadow p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Analytics Filters</h2>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700">Date From</label>
            <input
              type="date"
              value={dateFrom}
              onChange={(e) => setDateFrom(e.target.value)}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Date To</label>
            <input
              type="date"
              value={dateTo}
              onChange={(e) => setDateTo(e.target.value)}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700">Granularity</label>
            <select
              value={granularity}
              onChange={(e) => setGranularity(e.target.value as 'day' | 'week' | 'month')}
              className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
            >
              <option value="day">Daily</option>
              <option value="week">Weekly</option>
              <option value="month">Monthly</option>
            </select>
          </div>
          <div className="flex items-end">
            <button
              onClick={() => refetch()}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700"
            >
              Apply
            </button>
          </div>
        </div>
      </div>

      {isLoading && (
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
          <p className="mt-2 text-sm text-gray-500">Loading analytics...</p>
        </div>
      )}

      {error && <div className="text-red-500 p-4">{error}</div>}

      {analytics && !isLoading && (
        <>
          {/* Overview Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
            <div className="bg-white rounded-lg shadow p-4">
              <p className="text-xs text-gray-500">Total Commissions</p>
              <p className="text-xl font-bold">{analytics.overview.totalCommissions}</p>
            </div>
            <div className="bg-white rounded-lg shadow p-4">
              <p className="text-xs text-gray-500">Total Amount</p>
              <p className="text-xl font-bold">${analytics.overview.totalAmount.toFixed(2)}</p>
            </div>
            <div className="bg-white rounded-lg shadow p-4">
              <p className="text-xs text-gray-500">Average</p>
              <p className="text-xl font-bold">${analytics.overview.averageCommission.toFixed(2)}</p>
            </div>
            <div className="bg-white rounded-lg shadow p-4">
              <p className="text-xs text-gray-500">Max</p>
              <p className="text-xl font-bold">${analytics.overview.maxCommission.toFixed(2)}</p>
            </div>
            <div className="bg-white rounded-lg shadow p-4">
              <p className="text-xs text-gray-500">Min</p>
              <p className="text-xl font-bold">${analytics.overview.minCommission.toFixed(2)}</p>
            </div>
            <div className="bg-white rounded-lg shadow p-4">
              <p className="text-xs text-gray-500">Growth</p>
              <p className={`text-xl font-bold ${analytics.overview.commissionGrowth >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {analytics.overview.commissionGrowth >= 0 ? '+' : ''}{analytics.overview.commissionGrowth.toFixed(1)}%
              </p>
            </div>
          </div>

          {/* By Type */}
          {analytics.byType.length > 0 && (
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">By Type</h3>
              <div className="space-y-3">
                {analytics.byType.map((item) => (
                  <div key={item.type} className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-700 w-32">{item.type}</span>
                    <div className="flex-1 mx-4">
                      <div className="bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-indigo-600 rounded-full h-2"
                          style={{ width: `${item.percentage}%` }}
                        ></div>
                      </div>
                    </div>
                    <span className="text-sm text-gray-500 w-24 text-right">{item.count}</span>
                    <span className="text-sm font-medium w-32 text-right">${item.amount.toFixed(2)}</span>
                    <span className="text-xs text-gray-400 w-16 text-right">({item.percentage.toFixed(1)}%)</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Status Distribution */}
          {analytics.statusDistribution.length > 0 && (
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Status Distribution</h3>
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                {analytics.statusDistribution.map((item) => (
                  <div key={item.status} className="text-center p-4 bg-gray-50 rounded-lg">
                    <div className={`text-2xl font-bold ${
                      item.status === 'PAID' ? 'text-green-600' :
                      item.status === 'REVERSED' ? 'text-red-600' :
                      item.status === 'PENDING' || item.status === 'CALCULATED' ? 'text-yellow-600' :
                      'text-gray-600'
                    }`}>
                      {item.count}
                    </div>
                    <div className="text-sm text-gray-500 mt-1">{item.status}</div>
                    <div className="text-xs text-gray-400">${item.amount.toFixed(2)}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Top Users */}
          {analytics.topUsers.length > 0 && (
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Top Users by Commission</h3>
              <div className="overflow-x-auto">
                <table className="min-w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-2 text-sm font-medium text-gray-500">#</th>
                      <th className="text-left py-2 text-sm font-medium text-gray-500">User ID</th>
                      <th className="text-right py-2 text-sm font-medium text-gray-500">Count</th>
                      <th className="text-right py-2 text-sm font-medium text-gray-500">Total Amount</th>
                    </tr>
                  </thead>
                  <tbody>
                    {analytics.topUsers.map((user, index) => (
                      <tr key={user.userId} className="border-b last:border-0">
                        <td className="py-2 text-sm text-gray-500">{index + 1}</td>
                        <td className="py-2 text-sm text-gray-900">{user.userId}</td>
                        <td className="py-2 text-sm text-right text-gray-500">{user.count}</td>
                        <td className="py-2 text-sm text-right font-medium">${user.totalAmount.toFixed(2)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Trend */}
          {analytics.trend.length > 0 && (
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Commission Trend</h3>
              <div className="overflow-x-auto">
                <table className="min-w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-2 text-sm font-medium text-gray-500">Period</th>
                      <th className="text-right py-2 text-sm font-medium text-gray-500">Count</th>
                      <th className="text-right py-2 text-sm font-medium text-gray-500">Amount</th>
                    </tr>
                  </thead>
                  <tbody>
                    {analytics.trend.map((item) => (
                      <tr key={item.period} className="border-b last:border-0">
                        <td className="py-2 text-sm text-gray-900">{item.period}</td>
                        <td className="py-2 text-sm text-right text-gray-500">{item.count}</td>
                        <td className="py-2 text-sm text-right font-medium">${item.amount.toFixed(2)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
};

