'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import {
  ArrowLeft,
  Workflow,
  Bot,
  Cog,
  ListFilter,
  History,
  FileText,
  Settings,
  CheckCircle2,
  XCircle,
  Clock,
  Zap,
  Brain,
  Activity,
} from 'lucide-react';

interface ExecutionStats {
  total: number;
  completed: number;
  failed: number;
  skipped: number;
  robotic: number;
  ai: number;
  hybrid: number;
}

export default function WorkflowDashboardPage() {
  const [enabled, setEnabled] = useState(false);
  const [stats, setStats] = useState<ExecutionStats>({ total: 0, completed: 0, failed: 0, skipped: 0, robotic: 0, ai: 0, hybrid: 0 });
  const [recentExecutions, setRecentExecutions] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);

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

  const loadDashboard = async () => {
    setIsLoading(true);
    try {
      const [settingsRes, execRes] = await Promise.all([
        fetch('/api/workflow/settings'),
        fetch('/api/workflow/executions?limit=10'),
      ]);

      if (settingsRes.ok) {
        const settings = await settingsRes.json();
        setEnabled(settings.workflow_engine_enabled?.value ?? false);
      }

      if (execRes.ok) {
        const execData = await execRes.json();
        setRecentExecutions(execData.data || []);

        // Calculate stats from recent executions
        const all = execData.data || [];
        setStats({
          total: execData.total || 0,
          completed: all.filter((e: any) => e.status === 'completed').length,
          failed: all.filter((e: any) => e.status === 'failed').length,
          skipped: all.filter((e: any) => e.status === 'skipped').length,
          robotic: all.filter((e: any) => e.classification_method === 'robotic').length,
          ai: all.filter((e: any) => e.classification_method === 'ai').length,
          hybrid: all.filter((e: any) => e.classification_method === 'hybrid').length,
        });
      }
    } catch (error) {
      console.error('Failed to load dashboard:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const toggleEngine = async () => {
    try {
      const newValue = !enabled;
      await fetch('/api/workflow/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ workflow_engine_enabled: newValue }),
      });
      setEnabled(newValue);
    } catch (error) {
      console.error('Failed to toggle engine:', error);
    }
  };

  const navCards = [
    {
      title: 'Classification Rules',
      description: 'Keyword-based rules for ticket classification',
      href: '/admin/workflow/classification',
      icon: Bot,
      color: 'text-blue-500',
    },
    {
      title: 'Filter Rules',
      description: 'Exclusion/inclusion filters for ticket processing',
      href: '/admin/workflow/rules',
      icon: ListFilter,
      color: 'text-orange-500',
    },
    {
      title: 'AI Templates',
      description: 'Prompt templates for AI-assisted classification',
      href: '/admin/workflow/templates',
      icon: Brain,
      color: 'text-purple-500',
    },
    {
      title: 'Execution History',
      description: 'View past workflow executions and results',
      href: '/admin/workflow/history',
      icon: History,
      color: 'text-green-500',
    },
    {
      title: 'Settings',
      description: 'AI providers, thresholds, and delays',
      href: '/admin/workflow/settings',
      icon: Settings,
      color: 'text-gray-500',
    },
  ];

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/sync">
            <Button variant="ghost" size="sm">
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back
            </Button>
          </Link>
          <Workflow className="w-6 h-6" />
          <div>
            <h1 className="text-2xl font-bold">Workflow Engine</h1>
            <p className="text-sm text-muted-foreground">Automated ticket triage and classification</p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <span className="text-sm text-muted-foreground">
            {enabled ? 'Engine Active' : 'Engine Disabled'}
          </span>
          <Switch checked={enabled} onCheckedChange={toggleEngine} />
          <Badge variant={enabled ? 'default' : 'secondary'}>
            {enabled ? 'ON' : 'OFF'}
          </Badge>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Total Executions</p>
                <p className="text-2xl font-bold">{stats.total}</p>
              </div>
              <Activity className="w-8 h-8 text-muted-foreground/50" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Completed</p>
                <p className="text-2xl font-bold text-green-600">{stats.completed}</p>
              </div>
              <CheckCircle2 className="w-8 h-8 text-green-500/50" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Robotic</p>
                <p className="text-2xl font-bold text-blue-600">{stats.robotic}</p>
              </div>
              <Zap className="w-8 h-8 text-blue-500/50" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">AI/Hybrid</p>
                <p className="text-2xl font-bold text-purple-600">{stats.ai + stats.hybrid}</p>
              </div>
              <Brain className="w-8 h-8 text-purple-500/50" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Navigation Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {navCards.map((card) => (
          <Link key={card.href} href={card.href}>
            <Card className="hover:shadow-md transition-shadow cursor-pointer h-full">
              <CardHeader>
                <div className="flex items-center gap-3">
                  <card.icon className={`w-5 h-5 ${card.color}`} />
                  <CardTitle className="text-lg">{card.title}</CardTitle>
                </div>
                <CardDescription>{card.description}</CardDescription>
              </CardHeader>
            </Card>
          </Link>
        ))}
      </div>

      {/* Recent Executions */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Recent Executions</CardTitle>
              <CardDescription>Last 10 workflow runs</CardDescription>
            </div>
            <Link href="/admin/workflow/history">
              <Button variant="outline" size="sm">View All</Button>
            </Link>
          </div>
        </CardHeader>
        <CardContent>
          {recentExecutions.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-8">
              No executions yet. Workflow engine will process incoming tickets when enabled.
            </p>
          ) : (
            <div className="space-y-2">
              {recentExecutions.map((exec) => (
                <Link key={exec.id} href={`/admin/workflow/history?id=${exec.id}`}>
                  <div className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors cursor-pointer">
                    <div className="flex items-center gap-3">
                      {exec.status === 'completed' && <CheckCircle2 className="w-4 h-4 text-green-500" />}
                      {exec.status === 'failed' && <XCircle className="w-4 h-4 text-red-500" />}
                      {exec.status === 'skipped' && <Clock className="w-4 h-4 text-gray-500" />}
                      {exec.status === 'running' && <Activity className="w-4 h-4 text-blue-500 animate-pulse" />}
                      <div>
                        <span className="font-medium text-sm">
                          {exec.ticket_number ? `Ticket #${exec.ticket_number}` : `Entity ${exec.entity_id}`}
                        </span>
                        <span className="text-xs text-muted-foreground ml-2">
                          {new Date(exec.created_at).toLocaleString()}
                        </span>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {exec.branch && (
                        <Badge variant="outline" className="text-xs">{exec.branch}</Badge>
                      )}
                      <Badge variant={
                        exec.classification_method === 'robotic' ? 'default' :
                        exec.classification_method === 'ai' ? 'secondary' : 'outline'
                      } className="text-xs">
                        {exec.classification_method || 'n/a'}
                      </Badge>
                      {exec.duration_ms && (
                        <span className="text-xs text-muted-foreground">{exec.duration_ms}ms</span>
                      )}
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
