import { useState, useEffect } from 'react';
import PageMeta from '../../components/common/PageMeta';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { fetchCreditUsage, CreditUsageLog, fetchUsageLimits, LimitCard } from '../../services/api';
import { Card } from '../../components/ui/card';
import Badge from '../../components/ui/badge/Badge';

export default function Usage() {
  const toast = useToast();
  const [usageLogs, setUsageLogs] = useState<CreditUsageLog[]>([]);
  const [limits, setLimits] = useState<LimitCard[]>([]);
  const [loading, setLoading] = useState(true);
  const [limitsLoading, setLimitsLoading] = useState(true);

  useEffect(() => {
    loadUsage();
    loadLimits();
  }, []);

  const loadUsage = async () => {
    try {
      setLoading(true);
      const response = await fetchCreditUsage({ page: 1 });
      setUsageLogs(response.results || []);
    } catch (error: any) {
      toast.error(`Failed to load usage logs: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const loadLimits = async () => {
    try {
      setLimitsLoading(true);
      const response = await fetchUsageLimits();
      console.log('Usage limits response:', response);
      setLimits(response.limits || []);
      if (!response.limits || response.limits.length === 0) {
        console.warn('No limits data received from API');
      }
    } catch (error: any) {
      console.error('Error loading usage limits:', error);
      toast.error(`Failed to load usage limits: ${error.message}`);
      setLimits([]);
    } finally {
      setLimitsLoading(false);
    }
  };

  const groupedLimits = {
    planner: limits.filter(l => l.category === 'planner'),
    writer: limits.filter(l => l.category === 'writer'),
    images: limits.filter(l => l.category === 'images'),
    ai: limits.filter(l => l.category === 'ai'),
    general: limits.filter(l => l.category === 'general'),
  };

  // Debug info
  console.log('[Usage Component] Render state:', {
    limitsLoading,
    limitsCount: limits.length,
    groupedLimits,
    plannerCount: groupedLimits.planner.length,
    writerCount: groupedLimits.writer.length,
    imagesCount: groupedLimits.images.length,
    aiCount: groupedLimits.ai.length,
    generalCount: groupedLimits.general.length,
  });

  return (
    <div className="p-6">
      <PageMeta title="Usage" description="Monitor your plan limits and usage statistics" />
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Acoount Limits Usage 2</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">Monitor your plan limits and usage statistics</p>
      </div>

      {/* Debug Info - Remove in production */}
      {import.meta.env.DEV && (
        <Card className="p-4 mb-4 bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800">
          <div className="text-xs text-gray-600 dark:text-gray-400">
            <strong>Debug:</strong> Loading={limitsLoading ? 'Yes' : 'No'}, Limits={limits.length}, 
            Planner={groupedLimits.planner.length}, Writer={groupedLimits.writer.length}, 
            Images={groupedLimits.images.length}, AI={groupedLimits.ai.length}, General={groupedLimits.general.length}
          </div>
        </Card>
      )}

      {/* Limit Cards by Category */}
      {limitsLoading ? (
        <Card className="p-6 mb-8">
          <div className="flex items-center justify-center h-32">
            <div className="text-gray-500">Loading limits...</div>
          </div>
        </Card>
      ) : limits.length === 0 ? (
        <Card className="p-6 mb-8">
          <div className="text-center text-gray-500 dark:text-gray-400">
            <p className="mb-2 font-medium">No usage limits data available.</p>
            <p className="text-sm">The API endpoint may not be responding or your account may not have a plan configured.</p>
            <p className="text-xs mt-2 text-gray-400">Check browser console for errors. Endpoint: /v1/billing/credits/usage/limits/</p>
          </div>
        </Card>
      ) : (
        <div className="space-y-6 mb-8">
          {/* Planner Limits */}
          {groupedLimits.planner.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Planner Limits</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {groupedLimits.planner.map((limit, idx) => (
                  <LimitCardComponent key={idx} limit={limit} />
                ))}
              </div>
            </div>
          )}

          {/* Writer Limits */}
          {groupedLimits.writer.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Writer Limits</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {groupedLimits.writer.map((limit, idx) => (
                  <LimitCardComponent key={idx} limit={limit} />
                ))}
              </div>
            </div>
          )}

          {/* Image Limits */}
          {groupedLimits.images.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Image Generation Limits</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {groupedLimits.images.map((limit, idx) => (
                  <LimitCardComponent key={idx} limit={limit} />
                ))}
              </div>
            </div>
          )}

          {/* AI Credits */}
          {groupedLimits.ai.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">AI Credits</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {groupedLimits.ai.map((limit, idx) => (
                  <LimitCardComponent key={idx} limit={limit} />
                ))}
              </div>
            </div>
          )}

          {/* General Limits */}
          {groupedLimits.general.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">General Limits</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {groupedLimits.general.map((limit, idx) => (
                  <LimitCardComponent key={idx} limit={limit} />
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Usage Logs Table */}
      <div className="mb-6">
        <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Usage Logs</h2>
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-gray-500">Loading...</div>
          </div>
        ) : (
          <Card className="p-6">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Date</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Operation</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Credits Used</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Model</th>
                    <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 dark:text-gray-300">Cost (USD)</th>
                  </tr>
                </thead>
                <tbody>
                  {usageLogs.map((log) => (
                    <tr key={log.id} className="border-b border-gray-100 dark:border-gray-800">
                      <td className="py-3 px-4 text-sm text-gray-900 dark:text-white">
                        {new Date(log.created_at).toLocaleString()}
                      </td>
                      <td className="py-3 px-4">
                        <Badge variant="light" color="primary">{log.operation_type_display}</Badge>
                      </td>
                      <td className="py-3 px-4 text-sm font-medium text-gray-900 dark:text-white">
                        {log.credits_used}
                      </td>
                      <td className="py-3 px-4 text-sm text-gray-600 dark:text-gray-400">
                        {log.model_used || 'N/A'}
                      </td>
                      <td className="py-3 px-4 text-sm text-gray-600 dark:text-gray-400">
                        {log.cost_usd ? `$${parseFloat(log.cost_usd).toFixed(4)}` : 'N/A'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

// Limit Card Component
function LimitCardComponent({ limit }: { limit: LimitCard }) {
  const getCategoryColor = (category: string) => {
    switch (category) {
      case 'planner': return 'blue';
      case 'writer': return 'green';
      case 'images': return 'purple';
      case 'ai': return 'orange';
      case 'general': return 'gray';
      default: return 'gray';
    }
  };

  const getUsageStatus = (percentage: number) => {
    if (percentage >= 90) return 'danger';
    if (percentage >= 75) return 'warning';
    return 'success';
  };

  const percentage = Math.min(limit.percentage, 100);
  const status = getUsageStatus(percentage);
  const color = getCategoryColor(limit.category);
  
  const statusColorClass = status === 'danger' 
    ? 'bg-red-500' 
    : status === 'warning' 
    ? 'bg-yellow-500' 
    : 'bg-green-500';
  
  const statusTextColor = status === 'danger'
    ? 'text-red-600 dark:text-red-400'
    : status === 'warning'
    ? 'text-yellow-600 dark:text-yellow-400'
    : 'text-green-600 dark:text-green-400';

  return (
    <Card className="p-4">
      <div className="flex items-center justify-between mb-2">
        <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">{limit.title}</h3>
        <Badge variant="light" color={color as any}>{limit.category}</Badge>
      </div>
      <div className="mb-3">
        <div className="flex items-baseline gap-2">
          <span className="text-2xl font-bold text-gray-900 dark:text-white">{limit.used.toLocaleString()}</span>
          <span className="text-sm text-gray-500 dark:text-gray-400">/ {limit.limit.toLocaleString()}</span>
          <span className="text-xs text-gray-400 dark:text-gray-500">{limit.unit}</span>
        </div>
        <div className="mt-2">
          <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
            <div
              className={`h-2 rounded-full ${statusColorClass}`}
              style={{ width: `${percentage}%` }}
            />
          </div>
        </div>
      </div>
      <div className="flex items-center justify-between text-xs">
        <span className={statusTextColor}>
          {limit.available.toLocaleString()} available
        </span>
        <span className="text-gray-500 dark:text-gray-400">
          {percentage.toFixed(1)}% used
        </span>
      </div>
    </Card>
  );
}
