'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { GitBranch, Clock, CheckCircle, AlertTriangle, Play, ChevronRight, Layers } from 'lucide-react';

interface WorkflowStep {
  id: string;
  name: string;
  description: string | null;
  order: number;
  action: Record<string, unknown>;
  conditions: unknown;
  nextSteps: unknown;
}

interface Workflow {
  id: string;
  name: string;
  description: string | null;
  status: string;
  trigger: Record<string, unknown>;
  createdAt: string;
  workflowSteps: WorkflowStep[];
  _count: { WorkflowExecution: number };
}

const STATUS_DISPLAY: Record<string, { label: string; color: string; icon: typeof Clock }> = {
  draft: { label: 'Draft', color: 'text-gray-400 bg-gray-400/10', icon: Clock },
  active: { label: 'Active', color: 'text-green-400 bg-green-400/10', icon: CheckCircle },
  paused: { label: 'Paused', color: 'text-amber-400 bg-amber-400/10', icon: AlertTriangle },
  archived: { label: 'Archived', color: 'text-gray-500 bg-gray-500/10', icon: Clock },
};

export default function WorkflowListPage() {
  const [workflows, setWorkflows] = useState<Workflow[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/dark-factory/workflows')
      .then(r => r.json())
      .then(data => { setWorkflows(data.workflows || []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white flex items-center gap-2">
          <GitBranch className="w-6 h-6 text-sky-400" /> Workflow Diagrams
        </h1>
        <p className="text-gray-400 mt-1">Visualize and edit workflow step flows with interactive diagrams</p>
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">Loading workflows...</div>
      ) : workflows.length === 0 ? (
        <div className="text-center py-16 border border-dashed border-slate-700 rounded-xl">
          <GitBranch className="w-12 h-12 text-gray-600 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-400">No workflows found</h3>
          <p className="text-gray-500 mt-1">Workflows are created through the intake pipeline or agent system</p>
        </div>
      ) : (
        <div className="space-y-3">
          {workflows.map(wf => {
            const st = STATUS_DISPLAY[wf.status] || STATUS_DISPLAY.draft;
            const StatusIcon = st.icon;
            const triggerType = typeof wf.trigger === 'object' && wf.trigger !== null
              ? (wf.trigger as Record<string, string>).type || 'manual'
              : 'manual';
            return (
              <Link key={wf.id} href={`/dark-factory/app/workflows/${wf.id}`}
                className="block p-4 bg-slate-900 border border-slate-700 rounded-xl hover:border-sky-500/30 transition-colors">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <h3 className="text-white font-semibold">{wf.name}</h3>
                    {wf.description && <p className="text-gray-400 text-sm mt-1 line-clamp-2">{wf.description}</p>}
                    <div className="flex items-center gap-3 mt-2">
                      <span className="flex items-center gap-1 text-xs text-gray-500">
                        <Layers className="w-3 h-3" /> {wf.workflowSteps.length} steps
                      </span>
                      <span className="flex items-center gap-1 text-xs text-gray-500">
                        <Play className="w-3 h-3" /> {wf._count.WorkflowExecution} runs
                      </span>
                      <span className="text-xs text-gray-600">Trigger: {triggerType}</span>
                    </div>
                    {/* Mini flow preview */}
                    {wf.workflowSteps.length > 0 && (
                      <div className="flex items-center gap-1 mt-2 overflow-x-auto">
                        {wf.workflowSteps.slice(0, 5).map((step, i) => (
                          <div key={step.id} className="flex items-center gap-1">
                            <span className="px-2 py-0.5 bg-slate-800 border border-slate-700 rounded text-[10px] text-gray-400 whitespace-nowrap">
                              {step.name}
                            </span>
                            {i < Math.min(wf.workflowSteps.length, 5) - 1 && (
                              <ChevronRight className="w-3 h-3 text-gray-700 flex-shrink-0" />
                            )}
                          </div>
                        ))}
                        {wf.workflowSteps.length > 5 && (
                          <span className="text-[10px] text-gray-600">+{wf.workflowSteps.length - 5} more</span>
                        )}
                      </div>
                    )}
                  </div>
                  <div className={`flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium ${st.color}`}>
                    <StatusIcon className="w-3.5 h-3.5" />
                    {st.label}
                  </div>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
