/**
 * Admin Credit Costs Page
 * Manage credit pricing per billable action
 */
import { useEffect, useState } from 'react';
import { AlertCircle, Loader2, Check } from 'lucide-react';
import PageMeta from '../../components/common/PageMeta';
import { Card } from '../../components/ui/card';
import Button from '../../components/ui/button/Button';
import {
  getCreditCosts,
  updateCreditCosts,
  type CreditCostConfig,
} from '../../services/billing.api';

export default function AdminCreditCostsPage() {
  const [costs, setCosts] = useState<CreditCostConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [savingId, setSavingId] = useState<number | null>(null);
  const [error, setError] = useState<string>('');

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

  const loadCosts = async () => {
    try {
      setLoading(true);
      const data = await getCreditCosts();
      setCosts(data.results || []);
    } catch (err: any) {
      setError(err.message || 'Failed to load credit costs');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async (cost: CreditCostConfig) => {
    try {
      setSavingId(cost.id);
      await updateCreditCosts([
        { operation_type: cost.operation_type, credits_cost: Number(cost.credits_cost) || 0 },
      ]);
      await loadCosts();
    } catch (err: any) {
      setError(err.message || 'Failed to update credit cost');
    } finally {
      setSavingId(null);
    }
  };

  const updateLocalCost = (id: number, value: string) => {
    setCosts((prev) =>
      prev.map((c) => (c.id === id ? { ...c, credits_cost: value as any } : c)),
    );
  };

  if (loading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  return (
    <div className="p-6">
      <PageMeta title="Admin - Credit Costs" description="Manage credit pricing per action" />

      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Credit Costs</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Configure credits required for each billable operation.
        </p>
      </div>

      {error && (
        <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5 text-red-600" />
          <p className="text-red-800 dark:text-red-200">{error}</p>
        </div>
      )}

      <Card className="overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Operation
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Display Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Credits Cost
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Unit
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Description
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {costs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-8 text-center text-gray-500">
                    No credit costs configured
                  </td>
                </tr>
              ) : (
                costs.map((cost) => (
                  <tr key={cost.id} className="hover:bg-gray-50 dark:hover:bg-gray-800">
                    <td className="px-6 py-4 text-sm font-mono text-gray-700 dark:text-gray-300">
                      {cost.operation_type}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-900 dark:text-white">
                      {cost.display_name || '-'}
                    </td>
                    <td className="px-6 py-4">
                      <input
                        type="number"
                        value={cost.credits_cost as any}
                        onChange={(e) => updateLocalCost(cost.id, e.target.value)}
                        className="w-24 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
                      />
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600 dark:text-gray-400">
                      {cost.unit}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600 dark:text-gray-400 max-w-md">
                      {cost.description}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <Button
                        size="sm"
                        variant="primary"
                        tone="brand"
                        startIcon={savingId === cost.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
                        disabled={savingId === cost.id}
                        onClick={() => handleSave(cost)}
                      >
                        {savingId === cost.id ? 'Saving...' : 'Save'}
                      </Button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

