'use client';

import { createProxyFetch } from '@/lib/proxy-fetch';

import { useState, useEffect, useCallback } from 'react';
import { Coins, Plus, MoreHorizontal, AlertTriangle, TrendingUp, Trash2 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

interface BudgetPolicy {
  id: string;
  name: string;
  scope: string;
  period: string;
  limitAmount: number;
  currentSpend?: number;
  alertThresholdPercent: number;
  status: string;
  createdAt: string;
}

interface BudgetAlert {
  id: string;
  policyId: string;
  policyName?: string;
  type: string;
  message: string;
  currentSpend: number;
  limitAmount: number;
  createdAt: string;
  acknowledged: boolean;
}

function formatCurrency(amount: number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

const apiFetch = createProxyFetch('/api/ai-budgets');

export default function AIBudgetsPage() {
  const [policies, setPolicies] = useState<BudgetPolicy[]>([]);
  const [alerts, setAlerts] = useState<BudgetAlert[]>([]);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<'policies' | 'alerts'>('policies');
  const [showCreate, setShowCreate] = useState(false);
  const [creating, setCreating] = useState(false);

  // Create form
  const [newName, setNewName] = useState('');
  const [newScope, setNewScope] = useState('global');
  const [newPeriod, setNewPeriod] = useState('monthly');
  const [newLimit, setNewLimit] = useState('100');
  const [newThreshold, setNewThreshold] = useState('80');

  const loadData = useCallback(async () => {
    setLoading(true);
    const [pData, aData] = await Promise.all([apiFetch('policies'), apiFetch('alerts')]);
    setPolicies(
      Array.isArray(pData?.policies) ? pData.policies : Array.isArray(pData) ? pData : []
    );
    setAlerts(Array.isArray(aData?.alerts) ? aData.alerts : Array.isArray(aData) ? aData : []);
    setLoading(false);
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  async function handleCreate() {
    setCreating(true);
    await apiFetch('policies', {
      method: 'POST',
      body: JSON.stringify({
        name: newName,
        scope: newScope,
        period: newPeriod,
        limitAmount: parseFloat(newLimit) || 100,
        alertThresholdPercent: parseInt(newThreshold) || 80,
      }),
    });
    setCreating(false);
    setShowCreate(false);
    setNewName('');
    setNewScope('global');
    setNewPeriod('monthly');
    setNewLimit('100');
    setNewThreshold('80');
    loadData();
  }

  async function handleDelete(id: string) {
    if (!confirm('Delete this budget policy?')) return;
    await apiFetch(`policies/${id}`, { method: 'DELETE' });
    loadData();
  }

  const totalSpend = policies.reduce((sum, p) => sum + (p.currentSpend ?? 0), 0);
  const totalBudget = policies.reduce((sum, p) => sum + p.limitAmount, 0);
  const unacknowledgedAlerts = alerts.filter(a => !a.acknowledged).length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">AI Budgets & Cost Management</h1>
          <p className="text-sm text-muted-foreground">
            Monitor AI spend, set budget policies, and manage cost alerts
          </p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="mr-2 h-4 w-4" /> Create Policy
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total Spend</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(totalSpend)}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Budget
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatCurrency(totalBudget)}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Utilization</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <div className="text-2xl font-bold">
                {totalBudget > 0 ? Math.round((totalSpend / totalBudget) * 100) : 0}%
              </div>
              <TrendingUp className="h-4 w-4 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Active Alerts
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <div className="text-2xl font-bold text-amber-600">{unacknowledgedAlerts}</div>
              {unacknowledgedAlerts > 0 && <AlertTriangle className="h-5 w-5 text-amber-500" />}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="flex gap-2">
        <Button
          variant={tab === 'policies' ? 'default' : 'outline'}
          size="sm"
          onClick={() => setTab('policies')}
        >
          Policies ({policies.length})
        </Button>
        <Button
          variant={tab === 'alerts' ? 'default' : 'outline'}
          size="sm"
          onClick={() => setTab('alerts')}
        >
          Alerts ({alerts.length})
        </Button>
      </div>

      {tab === 'policies' && (
        <Card>
          <CardContent className="p-0">
            {loading ? (
              <div className="p-8 text-center text-muted-foreground">Loading...</div>
            ) : policies.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                <Coins className="mx-auto mb-2 h-8 w-8 opacity-40" />
                No budget policies yet. Create one to start tracking AI spend.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Policy</TableHead>
                    <TableHead>Scope</TableHead>
                    <TableHead>Period</TableHead>
                    <TableHead>Spend / Limit</TableHead>
                    <TableHead>Utilization</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="w-[50px]" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {policies.map(p => {
                    const util =
                      p.limitAmount > 0
                        ? Math.round(((p.currentSpend ?? 0) / p.limitAmount) * 100)
                        : 0;
                    return (
                      <TableRow key={p.id}>
                        <TableCell className="font-medium">{p.name}</TableCell>
                        <TableCell>
                          <Badge variant="outline" className="capitalize">
                            {p.scope}
                          </Badge>
                        </TableCell>
                        <TableCell className="capitalize">{p.period}</TableCell>
                        <TableCell>
                          {formatCurrency(p.currentSpend ?? 0)} / {formatCurrency(p.limitAmount)}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <div className="h-2 w-20 rounded-full bg-gray-100">
                              <div
                                className={`h-2 rounded-full ${
                                  util >= 90
                                    ? 'bg-red-500'
                                    : util >= 70
                                      ? 'bg-amber-500'
                                      : 'bg-emerald-500'
                                }`}
                                style={{ width: `${Math.min(util, 100)}%` }}
                              />
                            </div>
                            <span className="text-xs text-muted-foreground">{util}%</span>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="outline"
                            className={
                              p.status === 'active'
                                ? 'bg-emerald-50 text-emerald-700 border-0'
                                : 'bg-gray-50 text-gray-600 border-0'
                            }
                          >
                            {p.status}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-8 w-8">
                                <MoreHorizontal className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem
                                onClick={() => handleDelete(p.id)}
                                className="text-destructive"
                              >
                                <Trash2 className="mr-2 h-4 w-4" /> Delete
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}

      {tab === 'alerts' && (
        <Card>
          <CardContent className="p-0">
            {alerts.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                <AlertTriangle className="mx-auto mb-2 h-8 w-8 opacity-40" />
                No budget alerts.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Alert</TableHead>
                    <TableHead>Spend / Limit</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {alerts.map(a => (
                    <TableRow key={a.id}>
                      <TableCell>
                        <div className="font-medium text-sm">{a.message}</div>
                        <p className="text-xs text-muted-foreground">
                          {a.policyName || a.policyId}
                        </p>
                      </TableCell>
                      <TableCell>
                        {formatCurrency(a.currentSpend)} / {formatCurrency(a.limitAmount)}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatDate(a.createdAt)}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant="outline"
                          className={
                            a.acknowledged
                              ? 'bg-gray-50 text-gray-600 border-0'
                              : 'bg-amber-50 text-amber-700 border-0'
                          }
                        >
                          {a.acknowledged ? 'Acknowledged' : 'Active'}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}

      {/* Create Policy Dialog */}
      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create Budget Policy</DialogTitle>
            <DialogDescription>
              Set a spending limit and alert threshold for AI operations.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Policy Name</Label>
              <Input
                placeholder="e.g. Monthly GPT-4 Budget"
                value={newName}
                onChange={e => setNewName(e.target.value)}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Scope</Label>
                <Select value={newScope} onValueChange={setNewScope}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="global">Global</SelectItem>
                    <SelectItem value="product">Per Product</SelectItem>
                    <SelectItem value="user">Per User</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Period</Label>
                <Select value={newPeriod} onValueChange={setNewPeriod}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="daily">Daily</SelectItem>
                    <SelectItem value="monthly">Monthly</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Limit (USD)</Label>
                <Input
                  type="number"
                  min="1"
                  step="0.01"
                  value={newLimit}
                  onChange={e => setNewLimit(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>Alert Threshold (%)</Label>
                <Input
                  type="number"
                  min="1"
                  max="100"
                  value={newThreshold}
                  onChange={e => setNewThreshold(e.target.value)}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreate} disabled={creating || !newName.trim()}>
              {creating ? 'Creating...' : 'Create Policy'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
