/**
 * Usage & Analytics Page
 * Tabs: Credit Usage, API Usage, Cost Breakdown
 */

import { useState, useEffect } from 'react';
import { TrendingUp, Activity, DollarSign } from 'lucide-react';
import PageMeta from '../../components/common/PageMeta';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { getUsageAnalytics, UsageAnalytics } from '../../services/billing.api';
import { Card } from '../../components/ui/card';
import Badge from '../../components/ui/badge/Badge';
import BillingUsagePanel from '../../components/billing/BillingUsagePanel';
import BillingBalancePanel from '../../components/billing/BillingBalancePanel';
import Button from '../../components/ui/button/Button';

type TabType = 'credits' | 'api' | 'costs';

export default function UsageAnalyticsPage() {
  const toast = useToast();
  const [activeTab, setActiveTab] = useState<TabType>('credits');
  const [analytics, setAnalytics] = useState<UsageAnalytics | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState(30);

  useEffect(() => {
    loadAnalytics();
  }, [period]);

  const loadAnalytics = async () => {
    try {
      setLoading(true);
      const data = await getUsageAnalytics(period);
      setAnalytics(data);
    } catch (error: any) {
      toast.error(`Failed to load usage analytics: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="p-6">
        <PageMeta title="Usage & Analytics" description="Analyze your usage patterns" />
        <div className="flex items-center justify-center h-64">
          <div className="text-gray-500">Loading...</div>
        </div>
      </div>
    );
  }

  const tabs = [
    { id: 'credits' as TabType, label: 'Credit Usage', icon: <TrendingUp className="w-4 h-4" /> },
    { id: 'balance' as TabType, label: 'Credit Balance', icon: <DollarSign className="w-4 h-4" /> },
    { id: 'api' as TabType, label: 'API Usage', icon: <Activity className="w-4 h-4" /> },
    { id: 'costs' as TabType, label: 'Cost Breakdown', icon: <DollarSign className="w-4 h-4" /> },
  ];

  return (
    <div className="p-6">
      <PageMeta title="Usage & Analytics" description="Analyze your usage patterns" />
      
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Usage & Analytics</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Monitor credit usage, API calls, and cost breakdown
        </p>
      </div>

      <div className="mb-6 flex items-center justify-between">
        {/* Tabs */}
        <div className="border-b border-gray-200 dark:border-gray-700">
          <nav className="-mb-px flex space-x-8">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex items-center gap-2 py-4 px-1 border-b-2 font-medium text-sm
                  ${activeTab === tab.id
                    ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400'
                  }
                `}
              >
                {tab.icon}
                {tab.label}
              </button>
            ))}
          </nav>
        </div>

        {/* Period Selector */}
        <div className="flex gap-2">
          {[7, 30, 90].map((value) => {
            const isActive = period === value;
            return (
              <Button
                key={value}
                size="sm"
                variant={isActive ? 'primary' : 'secondary'}
                tone={isActive ? 'brand' : 'neutral'}
                onClick={() => setPeriod(value)}
              >
                {value} Days
              </Button>
            );
          })}
        </div>
      </div>

      {/* Tab Content */}
      <div className="mt-6">
        {/* Credit Usage Tab */}
        {activeTab === 'credits' && (
          <div className="space-y-6">
            {/* Summary Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Credits Used</div>
                <div className="text-3xl font-bold text-red-600 dark:text-red-400">
                  {analytics?.total_usage.toLocaleString() || 0}
                </div>
              </Card>

              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Purchases</div>
                <div className="text-3xl font-bold text-green-600 dark:text-green-400">
                  {analytics?.total_purchases.toLocaleString() || 0}
                </div>
              </Card>

              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Current Balance</div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white">
                  {analytics?.current_balance.toLocaleString() || 0}
                </div>
              </Card>
            </div>

            {/* Usage by Type */}
            <Card className="p-6">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                Usage by Operation Type
              </h2>
              <div className="space-y-3">
                {analytics?.usage_by_type.map((item, idx) => (
                  <div key={idx} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="flex-1">
                      <Badge variant="light" color="error">
                        {item.transaction_type}
                      </Badge>
                      <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        {item.count} operations
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-lg font-bold text-red-600 dark:text-red-400">
                        {item.total.toLocaleString()} credits
                      </div>
                    </div>
                  </div>
                ))}
                {(!analytics?.usage_by_type || analytics.usage_by_type.length === 0) && (
                  <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                    No usage in this period
                  </div>
                )}
              </div>
            </Card>
            {/* Insert Billing usage panel below current credit-analytics content */}
            <div className="mt-6">
              <BillingUsagePanel />
            </div>
          </div>
        )}

        {/* Credit Balance Tab (billing/credits moved here) */}
        {activeTab === 'balance' && (
          <div className="space-y-6">
            <BillingBalancePanel />
          </div>
        )}

        {/* API Usage Tab */}
        {activeTab === 'api' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total API Calls</div>
                <div className="text-3xl font-bold text-blue-600 dark:text-blue-400">
                  {analytics?.usage_by_type.reduce((sum, item) => sum + item.count, 0).toLocaleString() || 0}
                </div>
              </Card>

              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Avg Calls/Day</div>
                <div className="text-3xl font-bold text-purple-600 dark:text-purple-400">
                  {Math.round((analytics?.usage_by_type.reduce((sum, item) => sum + item.count, 0) || 0) / period)}
                </div>
              </Card>

              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Success Rate</div>
                <div className="text-3xl font-bold text-green-600 dark:text-green-400">
                  98.5%
                </div>
              </Card>
            </div>

            <Card className="p-6">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                API Calls by Endpoint
              </h2>
              <div className="space-y-3">
                <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                  <div className="flex-1">
                    <div className="font-medium">/api/v1/content/generate</div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Content generation</div>
                  </div>
                  <div className="text-right">
                    <div className="text-lg font-bold">1,234</div>
                    <div className="text-xs text-gray-500">calls</div>
                  </div>
                </div>
                <div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                  <div className="flex-1">
                    <div className="font-medium">/api/v1/keywords/cluster</div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Keyword clustering</div>
                  </div>
                  <div className="text-right">
                    <div className="text-lg font-bold">567</div>
                    <div className="text-xs text-gray-500">calls</div>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        )}

        {/* Cost Breakdown Tab */}
        {activeTab === 'costs' && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Cost</div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white">
                  ${((analytics?.total_usage || 0) * 0.01).toFixed(2)}
                </div>
                <div className="text-xs text-gray-500 mt-1">Estimated USD</div>
              </Card>

              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Avg Cost/Day</div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white">
                  ${(((analytics?.total_usage || 0) * 0.01) / period).toFixed(2)}
                </div>
                <div className="text-xs text-gray-500 mt-1">Estimated USD</div>
              </Card>

              <Card className="p-6">
                <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Cost per Credit</div>
                <div className="text-3xl font-bold text-gray-900 dark:text-white">
                  $0.01
                </div>
                <div className="text-xs text-gray-500 mt-1">Average rate</div>
              </Card>
            </div>

            <Card className="p-6">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                Cost by Operation
              </h2>
              <div className="space-y-3">
                {analytics?.usage_by_type.map((item, idx) => (
                  <div key={idx} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div className="flex-1">
                      <div className="font-medium">{item.transaction_type}</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        {item.total.toLocaleString()} credits used
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-lg font-bold">${(item.total * 0.01).toFixed(2)}</div>
                      <div className="text-xs text-gray-500">USD</div>
                    </div>
                  </div>
                ))}
                {(!analytics?.usage_by_type || analytics.usage_by_type.length === 0) && (
                  <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                    No cost data available
                  </div>
                )}
              </div>
            </Card>
          </div>
        )}
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6 hidden">
        <Card className="p-6">
          <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Credits Used</div>
          <div className="text-3xl font-bold text-red-600 dark:text-red-400">
            {analytics?.total_usage.toLocaleString() || 0}
          </div>
        </Card>

        <Card className="p-6">
          <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Total Purchases</div>
          <div className="text-3xl font-bold text-green-600 dark:text-green-400">
            {analytics?.total_purchases.toLocaleString() || 0}
          </div>
        </Card>

        <Card className="p-6">
          <div className="text-sm text-gray-600 dark:text-gray-400 mb-1">Current Balance</div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {analytics?.current_balance.toLocaleString() || 0}
          </div>
        </Card>
      </div>
    </div>
  );
}
