'use client';

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

import { useState, useEffect, useCallback } from 'react';
import {
  FlaskConical,
  Plus,
  MoreHorizontal,
  Play,
  Trash2,
  CheckCircle2,
  XCircle,
  Clock,
} 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 { Textarea } from '@/components/ui/textarea';
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';

interface EvalSuite {
  id: string;
  name: string;
  description?: string;
  agentId?: string;
  testCaseCount: number;
  lastRunStatus?: string;
  lastRunScore?: number;
  lastRunAt?: string;
  createdAt: string;
}

const statusConfig: Record<string, { color: string; icon: typeof Clock }> = {
  passed: { color: 'bg-emerald-50 text-emerald-700', icon: CheckCircle2 },
  failed: { color: 'bg-red-50 text-red-700', icon: XCircle },
  running: { color: 'bg-blue-50 text-blue-700', icon: Clock },
  pending: { color: 'bg-gray-50 text-gray-600', icon: Clock },
};

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

const apiFetch = createProxyFetch('/api/agent-evals');

export default function AgentEvalsPage() {
  const [suites, setSuites] = useState<EvalSuite[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState('');
  const [newDesc, setNewDesc] = useState('');

  const loadData = useCallback(async () => {
    setLoading(true);
    const data = await apiFetch('suites');
    setSuites(Array.isArray(data?.suites) ? data.suites : Array.isArray(data) ? data : []);
    setLoading(false);
  }, []);

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

  async function handleCreate() {
    setCreating(true);
    await apiFetch('suites', {
      method: 'POST',
      body: JSON.stringify({ name: newName, description: newDesc }),
    });
    setCreating(false);
    setShowCreate(false);
    setNewName('');
    setNewDesc('');
    loadData();
  }

  async function handleRun(id: string) {
    await apiFetch(`suites/${id}/runs`, { method: 'POST' });
    loadData();
  }

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

  const passedCount = suites.filter(s => s.lastRunStatus === 'passed').length;
  const failedCount = suites.filter(s => s.lastRunStatus === 'failed').length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Agent Evaluations</h1>
          <p className="text-sm text-muted-foreground">
            Create and run evaluation suites for AI agents
          </p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="mr-2 h-4 w-4" /> New Eval Suite
        </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 Suites
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{suites.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Passed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-emerald-600">{passedCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Failed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">{failedCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Test Cases
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {suites.reduce((sum, s) => sum + (s.testCaseCount ?? 0), 0)}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : suites.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <FlaskConical className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No evaluation suites yet.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Suite</TableHead>
                  <TableHead>Test Cases</TableHead>
                  <TableHead>Last Run</TableHead>
                  <TableHead>Score</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead className="w-[50px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {suites.map(s => {
                  const cfg = statusConfig[s.lastRunStatus || 'pending'] || statusConfig.pending;
                  const StatusIcon = cfg.icon;
                  return (
                    <TableRow key={s.id}>
                      <TableCell>
                        <div className="font-medium">{s.name}</div>
                        {s.description && (
                          <p className="text-xs text-muted-foreground truncate max-w-[250px]">
                            {s.description}
                          </p>
                        )}
                      </TableCell>
                      <TableCell>{s.testCaseCount}</TableCell>
                      <TableCell>
                        {s.lastRunStatus ? (
                          <Badge className={`${cfg.color} border-0 gap-1`}>
                            <StatusIcon className="h-3 w-3" />
                            {s.lastRunStatus}
                          </Badge>
                        ) : (
                          <span className="text-xs text-muted-foreground">Never run</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {s.lastRunScore != null ? (
                          <span
                            className={`font-bold ${(s.lastRunScore ?? 0) >= 80 ? 'text-emerald-600' : (s.lastRunScore ?? 0) >= 50 ? 'text-amber-600' : 'text-red-600'}`}
                          >
                            {s.lastRunScore}%
                          </span>
                        ) : (
                          '—'
                        )}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatDate(s.createdAt)}
                      </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={() => handleRun(s.id)}>
                              <Play className="mr-2 h-4 w-4" />
                              Run
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleDelete(s.id)}
                              className="text-red-600"
                            >
                              <Trash2 className="mr-2 h-4 w-4" />
                              Delete
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>New Evaluation Suite</DialogTitle>
            <DialogDescription>Create a test suite to evaluate AI agent quality.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Suite Name</Label>
              <Input
                placeholder="e.g. Customer Support Agent v2"
                value={newName}
                onChange={e => setNewName(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                placeholder="What this suite tests..."
                value={newDesc}
                onChange={e => setNewDesc(e.target.value)}
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreate} disabled={creating || !newName.trim()}>
              {creating ? 'Creating...' : 'Create'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
