/**
 * Credit Cost Breakdown Panel
 * Displays cost per operation and total costs
 */

import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { DollarSign, TrendingUp, AlertCircle } from 'lucide-react';
import Badge from '../ui/badge/Badge';
import { getCreditUsageSummary } from '../../services/billing.api';
import { useToast } from '../ui/toast/ToastContainer';

interface OperationData {
  credits: number;
  cost: number;
  count: number;
}

interface CreditUsageSummary {
  total_credits_used: number;
  total_cost_usd: string;
  by_operation: Record<string, OperationData>;
  by_model: Record<string, { credits: number; cost: number }>;
}

export default function CreditCostBreakdownPanel() {
  const toast = useToast();
  const [summary, setSummary] = useState<CreditUsageSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');
  const [period] = useState(30); // Last 30 days

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

  const loadAnalytics = async () => {
    try {
      setLoading(true);
      setError('');
      
      // Calculate date range for last N days
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - period);
      
      const data = await getCreditUsageSummary({
        start_date: startDate.toISOString(),
        end_date: endDate.toISOString(),
      });
      setSummary(data);
    } catch (err: any) {
      const message = err?.message || 'Failed to load cost analytics';
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="animate-pulse">
          <div className="h-32 bg-gray-200 dark:bg-gray-700 rounded-lg mb-4"></div>
          <div className="h-64 bg-gray-200 dark:bg-gray-700 rounded-lg"></div>
        </div>
      </div>
    );
  }

  if (error || !summary) {
    return (
      <Card className="p-6 text-center">
        <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
          Failed to Load Cost Data
        </h3>
        <p className="text-gray-600 dark:text-gray-400 mb-4">{error || 'Unknown error'}</p>
        <button
          onClick={loadAnalytics}
          className="px-4 py-2 bg-[var(--color-brand-500)] text-white rounded-lg hover:bg-[var(--color-brand-600)]"
        >
          Retry
        </button>
      </Card>
    );
  }

  // Calculate metrics
  const totalCost = parseFloat(summary.total_cost_usd) || 0;
  const totalCredits = summary.total_credits_used || 0;
  const totalOperations = Object.values(summary.by_operation).reduce((sum, op) => sum + op.count, 0);
  const avgCostPerDay = totalCost / period;

  // Convert by_operation to array and sort by cost
  const operationsList = Object.entries(summary.by_operation)
    .map(([type, data]) => ({
      operation_type: type,
      total: data.credits,
      count: data.count,
      cost_usd: data.cost,
    }))
    .sort((a, b) => b.cost_usd - a.cost_usd);

  // Color palette for different operation types
  const operationColors = [
    { bg: 'bg-brand-50 dark:bg-brand-900/20', text: 'text-brand-600 dark:text-brand-400', border: 'border-brand-500 dark:border-brand-400' },
    { bg: 'bg-success-50 dark:bg-success-900/20', text: 'text-success-600 dark:text-success-400', border: 'border-success-500 dark:border-success-400' },
    { bg: 'bg-info-50 dark:bg-info-900/20', text: 'text-info-600 dark:text-info-400', border: 'border-info-500 dark:border-info-400' },
    { bg: 'bg-purple-50 dark:bg-purple-900/20', text: 'text-purple-600 dark:text-purple-400', border: 'border-purple-500 dark:border-purple-400' },
    { bg: 'bg-warning-50 dark:bg-warning-900/20', text: 'text-warning-600 dark:text-warning-400', border: 'border-warning-500 dark:border-warning-400' },
    { bg: 'bg-teal-50 dark:bg-teal-900/20', text: 'text-teal-600 dark:text-teal-400', border: 'border-teal-500 dark:border-teal-400' },
  ];

  return (
    <div className="space-y-6">
      {/* Summary Cards - 4 columns */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="p-6 border-l-4 border-brand-500 dark:border-brand-400">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-brand-50 dark:bg-brand-900/20 rounded-lg">
              <DollarSign className="w-5 h-5 text-brand-500 dark:text-brand-400" />
            </div>
            <div className="text-sm text-gray-600 dark:text-gray-400">Total Cost</div>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            ${totalCost.toFixed(2)}
          </div>
          <div className="text-xs text-gray-500 mt-1">Last {period} days</div>
        </Card>

        <Card className="p-6 border-l-4 border-success-500 dark:border-success-400">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-success-50 dark:bg-success-900/20 rounded-lg">
              <TrendingUp className="w-5 h-5 text-success-500 dark:text-success-400" />
            </div>
            <div className="text-sm text-gray-600 dark:text-gray-400">Avg Cost/Day</div>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            ${avgCostPerDay.toFixed(2)}
          </div>
          <div className="text-xs text-gray-500 mt-1">Daily average</div>
        </Card>

        <Card className="p-6 border-l-4 border-purple-500 dark:border-purple-400">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
              <TrendingUp className="w-5 h-5 text-purple-500 dark:text-purple-400" />
            </div>
            <div className="text-sm text-gray-600 dark:text-gray-400">Total Operations</div>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {totalOperations.toLocaleString()}
          </div>
          <div className="text-xs text-gray-500 mt-1">API calls</div>
        </Card>

        <Card className="p-6 border-l-4 border-info-500 dark:border-info-400">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-info-50 dark:bg-info-900/20 rounded-lg">
              <DollarSign className="w-5 h-5 text-info-500 dark:text-info-400" />
            </div>
            <div className="text-sm text-gray-600 dark:text-gray-400">Total Credits</div>
          </div>
          <div className="text-3xl font-bold text-gray-900 dark:text-white">
            {totalCredits.toLocaleString()}
          </div>
          <div className="text-xs text-gray-500 mt-1">Credits used</div>
        </Card>
      </div>

      {/* Cost by Operation - 4 columns */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              Cost by Operation Type
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              Breakdown of credit costs per operation
            </p>
          </div>
          <Badge variant="soft" tone="brand">
            Last {period} days
          </Badge>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {operationsList.map((item, idx) => {
            const colorScheme = operationColors[idx % operationColors.length];
            const costUSD = item.cost_usd.toFixed(2);
            const avgPerOperation = item.count > 0 ? (item.total / item.count).toFixed(0) : '0';

            return (
              <Card 
                key={item.operation_type} 
                className={`p-4 border-l-4 ${colorScheme.border} hover:shadow-lg transition-all`}
              >
                <div className="mb-3">
                  <h4 className={`font-semibold ${colorScheme.text} mb-1`}>
                    {item.operation_type}
                  </h4>
                  <Badge variant="soft" tone="neutral" size="xs">
                    {item.count} ops
                  </Badge>
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Credits:</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {item.total.toLocaleString()}
                    </span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-gray-500 dark:text-gray-400">Avg/op:</span>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {avgPerOperation}
                    </span>
                  </div>
                  <div className="pt-2 mt-2 border-t border-gray-200 dark:border-gray-700">
                    <div className={`text-2xl font-bold ${colorScheme.text}`}>
                      ${costUSD}
                    </div>
                    <div className="text-xs text-gray-500">USD</div>
                  </div>
                </div>
              </Card>
            );
          })}
          
          {operationsList.length === 0 && (
            <div className="col-span-4 text-center py-12">
              <DollarSign className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-3" />
              <p className="text-gray-500 dark:text-gray-400">
                No cost data available for this period
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
