'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 {
  Workflow,
  Plus,
  Settings,
  Activity,
  CheckCircle2,
  XCircle,
  Edit,
  PlayCircle,
  PauseCircle,
} from 'lucide-react';
import { toast } from 'sonner';
import { PageHeader } from '@/components/navigation/page-header';

interface TicketWorkflow {
  id: number;
  name: string;
  description: string | null;
  is_active: boolean;
  trigger_event: string;
  sort_order: number;
  step_count?: number;
  executions_today?: number;
}

export default function WorkflowListPage() {
  const [globalEnabled, setGlobalEnabled] = useState(false);
  const [workflows, setWorkflows] = useState<TicketWorkflow[]>([]);
  const [isLoading, setIsLoading] = useState(true);

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

  const loadData = async () => {
    setIsLoading(true);
    try {
      const [settingsRes, workflowsRes] = await Promise.all([
        fetch('/api/workflow/settings'),
        fetch('/api/ticket-workflows'),
      ]);

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

      if (workflowsRes.ok) {
        const data = await workflowsRes.json();
        setWorkflows(data.workflows || []);
      }
    } catch (error) {
      console.error('Failed to load workflows:', error);
      toast.error('Failed to load workflows');
    } finally {
      setIsLoading(false);
    }
  };

  const toggleGlobalEngine = async () => {
    try {
      const newValue = !globalEnabled;
      const res = await fetch('/api/workflow/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ workflow_engine_enabled: newValue }),
      });

      if (res.ok) {
        setGlobalEnabled(newValue);
        toast.success(`Workflow engine ${newValue ? 'enabled' : 'disabled'}`);
      } else {
        toast.error('Failed to toggle engine');
      }
    } catch (error) {
      console.error('Failed to toggle engine:', error);
      toast.error('Failed to toggle engine');
    }
  };

  const toggleWorkflow = async (workflowId: number, currentState: boolean) => {
    try {
      const newState = !currentState;
      const res = await fetch(`/api/ticket-workflows/${workflowId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: newState }),
      });

      if (res.ok) {
        setWorkflows(prev =>
          prev.map(w => w.id === workflowId ? { ...w, is_active: newState } : w)
        );
        toast.success(`Workflow ${newState ? 'enabled' : 'disabled'}`);
      } else {
        toast.error('Failed to toggle workflow');
      }
    } catch (error) {
      console.error('Failed to toggle workflow:', error);
      toast.error('Failed to toggle workflow');
    }
  };

  return (
    <>
      <PageHeader
        title="Ticket Workflows"
        description="Automated ticket triage and classification"
        breadcrumbs={[{ label: 'Admin', href: '/admin' }, { label: 'Ticket Workflows' }]}
        accent
        actions={
          <Link href="/admin/workflow/create">
            <Button>
              <Plus className="w-4 h-4 mr-2" />
              Create Workflow
            </Button>
          </Link>
        }
      />
      <div className="container mx-auto p-6 space-y-6">
      {/* Master Control */}
      <Card className={globalEnabled ? 'border-green-500/50' : 'border-gray-300'}>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Settings className="w-5 h-5" />
                Master Control
              </CardTitle>
              <CardDescription>
                Emergency kill switch for all ticket workflows
              </CardDescription>
            </div>
            <div className="flex items-center gap-3">
              <span className="text-sm font-medium">
                {globalEnabled ? (
                  <span className="text-green-600 flex items-center gap-1">
                    <PlayCircle className="w-4 h-4" /> Enabled
                  </span>
                ) : (
                  <span className="text-gray-600 flex items-center gap-1">
                    <PauseCircle className="w-4 h-4" /> Disabled
                  </span>
                )}
              </span>
              <Switch checked={globalEnabled} onCheckedChange={toggleGlobalEngine} />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground">
            {globalEnabled ? (
              <>All active workflows will process incoming tickets. Individual workflows can be toggled below.</>
            ) : (
              <>All workflows are currently disabled. Enable the master switch to allow workflows to run.</>
            )}
          </p>
        </CardContent>
      </Card>

      {/* Workflow List */}
      <div className="space-y-4">
        {isLoading ? (
          <Card>
            <CardContent className="py-12 text-center text-muted-foreground">
              Loading workflows...
            </CardContent>
          </Card>
        ) : workflows.length === 0 ? (
          <Card>
            <CardContent className="py-12 text-center">
              <Workflow className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
              <p className="text-muted-foreground mb-4">No workflows yet</p>
              <Link href="/admin/workflow/create">
                <Button>
                  <Plus className="w-4 h-4 mr-2" />
                  Create Your First Workflow
                </Button>
              </Link>
            </CardContent>
          </Card>
        ) : (
          workflows.map((workflow) => (
            <Card
              key={workflow.id}
              className={workflow.is_active ? 'border-blue-500/50' : 'border-gray-300'}
            >
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <CardTitle className="text-lg">{workflow.name}</CardTitle>
                      <Badge
                        variant={workflow.is_active ? 'default' : 'secondary'}
                        className="text-xs"
                      >
                        {workflow.is_active ? 'Active' : 'Inactive'}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {workflow.trigger_event}
                      </Badge>
                    </div>
                    <CardDescription className="text-sm">
                      {workflow.description || 'No description'}
                    </CardDescription>
                  </div>

                  <div className="flex items-center gap-2 ml-4">
                    <Switch
                      checked={workflow.is_active}
                      onCheckedChange={() => toggleWorkflow(workflow.id, workflow.is_active)}
                      disabled={!globalEnabled}
                    />
                    <Link href={`/admin/workflow/${workflow.id}`}>
                      <Button variant="outline" size="sm">
                        <Edit className="w-4 h-4 mr-2" />
                        Edit
                      </Button>
                    </Link>
                  </div>
                </div>
              </CardHeader>

              <CardContent>
                <div className="flex items-center gap-6 text-sm">
                  <div className="flex items-center gap-2">
                    <Activity className="w-4 h-4 text-muted-foreground" />
                    <span className="text-muted-foreground">
                      {workflow.step_count || 0} steps
                    </span>
                  </div>

                  <div className="flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-500" />
                    <span className="text-muted-foreground">
                      {workflow.executions_today || 0} runs today
                    </span>
                  </div>

                  {!globalEnabled && (
                    <Badge variant="outline" className="text-xs text-orange-600">
                      Master switch disabled
                    </Badge>
                  )}
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      {/* Quick Links */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Related</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <Link href="/admin/workflow/classification-rules">
              <Button variant="outline" className="w-full justify-start">
                Classification Rules
              </Button>
            </Link>
            <Link href="/admin/workflow/ai-templates">
              <Button variant="outline" className="w-full justify-start">
                AI Templates
              </Button>
            </Link>
            <Link href="/admin/workflow/settings">
              <Button variant="outline" className="w-full justify-start">
                Workflow Settings
              </Button>
            </Link>
          </div>
        </CardContent>
      </Card>
      </div>
    </>
  );
}
