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';

// Credit costs per operation (Phase 0: Credit-only system)
const CREDIT_COSTS: Record<string, { cost: number | string; description: string }> = {
  clustering: { cost: 10, description: 'Per clustering request' },
  idea_generation: { cost: 15, description: 'Per cluster → ideas request' },
  content_generation: { cost: '1 per 100 words', description: 'Per 100 words generated' },
  image_prompt_extraction: { cost: 2, description: 'Per content piece' },
  image_generation: { cost: 5, description: 'Per image generated' },
  linking: { cost: 8, description: 'Per content piece' },
  optimization: { cost: '1 per 200 words', description: 'Per 200 words optimized' },
  site_structure_generation: { cost: 50, description: 'Per site blueprint' },
  site_page_generation: { cost: 20, description: 'Per page generated' },
};

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();
      setLimits(response.limits || []);
    } catch (error: any) {
      toast.error(`Failed to load usage limits: ${error.message}`);
      setLimits([]);
    } finally {
      setLimitsLoading(false);
    }
  };

  // Filter limits to show only credits and account management (Phase 0: Credit-only system)
  const creditLimits = limits.filter(l => l.category === 'credits');
  const accountLimits = limits.filter(l => l.category === 'account');

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

      {/* Credit Costs Reference */}
      <Card className="p-6 mb-6">
        <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Credit Costs per Operation</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Object.entries(CREDIT_COSTS).map(([operation, info]) => (
            <div key={operation} className="flex items-start justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
              <div className="flex-1">
                <div className="font-medium text-gray-900 dark:text-white capitalize">
                  {operation.replace(/_/g, ' ')}
                </div>
                <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                  {info.description}
                </div>
              </div>
              <div className="ml-4 text-right">
                <Badge variant="light" color="primary" className="font-semibold">
                  {typeof info.cost === 'number' ? `${info.cost} credits` : info.cost}
                </Badge>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Credit Limits */}
      {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>
      ) : (
        <div className="space-y-6 mb-8">
          {/* Credit Usage Limits */}
          {creditLimits.length > 0 && (
            <div>
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Credit Usage</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                {creditLimits.map((limit, idx) => (
                  <LimitCardComponent key={idx} limit={limit} />
                ))}
              </div>
            </div>
          )}

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

          {creditLimits.length === 0 && accountLimits.length === 0 && (
            <Card className="p-6">
              <div className="text-center text-gray-500 dark:text-gray-400">
                <p className="mb-2 font-medium">No limits data available.</p>
                <p className="text-sm">Your account may not have a plan configured.</p>
              </div>
            </Card>
          )}
        </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 'credits': return 'primary';
      case 'account': return 'gray';
      default: return 'gray';
    }
  };

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

  const percentage = limit.percentage !== null && limit.percentage !== undefined ? Math.min(limit.percentage, 100) : null;
  const status = getUsageStatus(percentage);
  const color = getCategoryColor(limit.category);
  
  const statusColorClass = status === 'danger' 
    ? 'bg-red-500' 
    : status === 'warning' 
    ? 'bg-yellow-500' 
    : status === 'info'
    ? 'bg-blue-500'
    : 'bg-green-500';
  
  const statusTextColor = status === 'danger'
    ? 'text-red-600 dark:text-red-400'
    : status === 'warning'
    ? 'text-yellow-600 dark:text-yellow-400'
    : status === 'info'
    ? 'text-blue-600 dark:text-blue-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">
          {limit.limit !== null && limit.limit !== undefined ? (
            <>
              <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-2xl font-bold text-gray-900 dark:text-white">
              {limit.available !== null && limit.available !== undefined ? limit.available.toLocaleString() : limit.used.toLocaleString()}
            </span>
          )}
          {limit.unit && (
            <span className="text-xs text-gray-400 dark:text-gray-500">{limit.unit}</span>
          )}
        </div>
        {percentage !== null && (
          <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">
        {limit.available !== null && limit.available !== undefined ? (
          <span className={statusTextColor}>
            {limit.available.toLocaleString()} available
          </span>
        ) : (
          <span className="text-gray-500 dark:text-gray-400">Current value</span>
        )}
        {percentage !== null && (
          <span className="text-gray-500 dark:text-gray-400">
            {percentage.toFixed(1)}% used
          </span>
        )}
      </div>
    </Card>
  );
}
