
import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { processEntryWithRules } from '@/lib/ruleEngine';
import { useToast } from '@/hooks/use-toast';
import { CheckCircle2, XCircle, AlertTriangle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';

export default function RuleTestDialog({ open, onOpenChange, ruleType }) {
  const { toast } = useToast();
  const [testPayload, setTestPayload] = useState('{\n  "amount": 100,\n  "description": "Home Depot",\n  "category": "Uncategorized"\n}');
  const [testResult, setTestResult] = useState(null);
  const [isTesting, setIsTesting] = useState(false);

  const handleTest = async () => {
    setIsTesting(true);
    setTestResult(null);
    try {
      const parsed = JSON.parse(testPayload);
      const result = await processEntryWithRules(parsed, ruleType);
      setTestResult(result);
      toast({ title: 'Test Complete', description: 'Rule engine processed the entry.' });
    } catch (err) {
      toast({ variant: 'destructive', title: 'Invalid JSON', description: 'Please check your payload format.' });
    } finally { setIsTesting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Test Global Rules Engine</DialogTitle>
          <DialogDescription>Simulate an incoming {ruleType ? ruleType.replace('_', ' ') : 'entry'} to see how global active rules will process it.</DialogDescription>
        </DialogHeader>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-4">
          <div className="space-y-2">
            <div className="text-sm font-semibold">Test Payload (JSON)</div>
            <Textarea value={testPayload} onChange={e => setTestPayload(e.target.value)} className="font-mono text-sm h-[300px] bg-muted/50" />
            <Button onClick={handleTest} className="w-full" disabled={isTesting}>{isTesting ? 'Testing...' : 'Run Test'}</Button>
          </div>
          
          <div className="space-y-2 flex flex-col h-full">
            <div className="text-sm font-semibold">Evaluation Results</div>
            <div className="flex-1 border rounded-md p-4 bg-muted/50 overflow-y-auto max-h-[300px]">
              {!testResult ? (
                <div className="text-muted-foreground text-sm h-full flex items-center justify-center italic">Run a test to see results</div>
              ) : (
                <div className="space-y-4">
                  <div className="flex items-center gap-2">
                    {testResult.blocked ? (
                      <Badge variant="destructive" className="flex items-center gap-1"><XCircle className="w-3 h-3" /> Blocked</Badge>
                    ) : (
                      <Badge className="bg-emerald-500 flex items-center gap-1"><CheckCircle2 className="w-3 h-3" /> Allowed</Badge>
                    )}
                  </div>
                  {testResult.blockReason && (
                    <div className="text-sm text-destructive bg-destructive/10 p-2 rounded border border-destructive/20 flex items-start gap-2">
                      <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" /><span>{testResult.blockReason}</span>
                    </div>
                  )}
                  <div>
                    <h5 className="text-xs font-bold text-muted-foreground uppercase mb-1">Execution Logs</h5>
                    {testResult.logs.length === 0 ? (
                      <div className="text-sm text-muted-foreground italic">No rules matched.</div>
                    ) : (
                      <ul className="text-xs font-mono bg-slate-900 text-slate-300 p-2 rounded space-y-1">
                        {testResult.logs.map((log, i) => (
                          <li key={i} className={log.startsWith('-') ? 'pl-2 text-emerald-400' : 'text-blue-300 font-semibold'}>{log}</li>
                        ))}
                      </ul>
                    )}
                  </div>
                  <div>
                    <h5 className="text-xs font-bold text-muted-foreground uppercase mb-1">Final Output Object</h5>
                    <pre className="text-xs bg-background p-2 rounded border overflow-x-auto">{JSON.stringify(testResult.entry, null, 2)}</pre>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
