'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Play,
  Square,
  Box,
  FileJson,
  Clock,
  Database,
  Info,
  RefreshCw,
  Maximize2,
  Minimize2,
  AlertTriangle,
} from 'lucide-react';
import { WeftSandboxProvider, useSandbox } from './sandbox-context';
import { ActionLogPanel } from './action-log-panel';
import { ApiDocsPanel } from './api-docs-panel';
import { MockDataEditor } from './mock-data-editor';
import { DemoOrderForm } from './demo-artifact';
import { WeftConfig } from '@/lib/weft';

type PanelTab = 'actions' | 'api' | 'data' | 'info';

// Default demo config
const DEMO_CONFIG: WeftConfig = {
  artifact: {
    id: 'demo-order-form-001',
    name: 'Order Form',
    generatedAt: new Date().toISOString(),
    intentHash: 'abc123def456',
    originalSpec: 'Create an order form with cart, customer info, and shipping options',
  },
  mockData: {
    customer: {
      id: 'cust-001',
      name: '',
      email: '',
    },
    products: [
      { id: 'prod-001', name: 'Familiar License', price: 299, stock: 100 },
      { id: 'prod-002', name: 'Enterprise Support', price: 499, stock: 50 },
      { id: 'prod-003', name: 'API Access Bundle', price: 199, stock: 200 },
    ],
    shipping: {
      standard: { days: 7, cost: 0 },
      express: { days: 2, cost: 25 },
    },
  },
  apiStubs: [
    {
      method: 'POST',
      endpoint: '/api/orders',
      description: 'Create a new order',
      requestSchema: {
        customer: 'object',
        items: 'array',
        shipping: 'string',
        total: 'number',
      },
      mockResponse: {
        success: true,
        orderId: 'ORD-2024-001',
        status: 'pending',
        estimatedDelivery: '2024-03-15',
      },
      mockStatus: 201,
      mockDelay: 800,
    },
    {
      method: 'GET',
      endpoint: '/api/products',
      description: 'Get all available products',
      mockResponse: {
        products: [
          { id: 'prod-001', name: 'Familiar License', price: 299, stock: 100 },
          { id: 'prod-002', name: 'Enterprise Support', price: 499, stock: 50 },
        ],
      },
      mockStatus: 200,
      mockDelay: 200,
    },
    {
      method: 'GET',
      endpoint: '/api/shipping/rates',
      description: 'Get shipping rates',
      mockResponse: {
        rates: [
          { method: 'standard', days: 7, cost: 0 },
          { method: 'express', days: 2, cost: 25 },
        ],
      },
      mockStatus: 200,
      mockDelay: 150,
    },
  ],
  navigation: {
    onSuccess: '/orders/confirmation',
    onCancel: '/cart',
    onError: '/checkout?error=true',
  },
};

function SandboxControls() {
  const { sandbox, isRunning, startSandbox, stopSandbox, errors } = useSandbox();

  if (!sandbox) return null;

  const artifact = sandbox.getArtifactInfo();

  return (
    <div className="flex items-center justify-between p-4 border-b border-white/10 bg-white/5">
      <div className="flex items-center gap-4">
        <div className="flex items-center gap-2">
          <Box className="w-5 h-5 text-brand-secondary-light" />
          <span className="font-semibold text-white">{artifact.name}</span>
          <span className="text-xs text-gray-500 font-mono">#{artifact.id.slice(-8)}</span>
        </div>

        <div className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium ${
          isRunning 
            ? 'bg-green-500/20 text-green-400' 
            : 'bg-gray-500/20 text-gray-400'
        }`}>
          <span className={`w-2 h-2 rounded-full ${isRunning ? 'bg-green-400 animate-pulse' : 'bg-gray-400'}`} />
          {isRunning ? 'Running' : 'Stopped'}
        </div>

        {errors.length > 0 && (
          <div className="flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium bg-red-500/20 text-red-400">
            <AlertTriangle className="w-3 h-3" />
            {errors.length} error{errors.length > 1 ? 's' : ''}
          </div>
        )}
      </div>

      <div className="flex items-center gap-2">
        {isRunning ? (
          <button
            onClick={stopSandbox}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 font-medium transition-colors"
          >
            <Square className="w-4 h-4" />
            Stop
          </button>
        ) : (
          <button
            onClick={startSandbox}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-green-500/20 hover:bg-green-500/30 text-green-400 font-medium transition-colors"
          >
            <Play className="w-4 h-4" />
            Start
          </button>
        )}
      </div>
    </div>
  );
}

function InfoPanel() {
  const { sandbox } = useSandbox();
  if (!sandbox) return null;

  const artifact = sandbox.getArtifactInfo();
  const navigation = sandbox.getNavigationConfig();

  return (
    <div className="h-full flex flex-col">
      <div className="flex items-center gap-3 px-4 py-3 border-b border-white/10">
        <Info className="w-5 h-5 text-brand" />
        <h3 className="font-semibold text-white">Artifact Info</h3>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-6">
        {/* Artifact Details */}
        <div>
          <h4 className="text-xs font-medium text-gray-400 uppercase mb-3">Artifact</h4>
          <div className="space-y-2">
            <div className="flex justify-between">
              <span className="text-gray-400">Name</span>
              <span className="text-white font-medium">{artifact.name}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">ID</span>
              <span className="text-brand font-mono text-sm">{artifact.id}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Generated</span>
              <span className="text-gray-300 text-sm">
                {new Date(artifact.generatedAt).toLocaleString()}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Intent Hash</span>
              <span className="text-brand-secondary-light font-mono text-sm">{artifact.intentHash}</span>
            </div>
          </div>
        </div>

        {/* Original Spec */}
        <div>
          <h4 className="text-xs font-medium text-gray-400 uppercase mb-3">Original Specification</h4>
          <div className="p-3 rounded-lg bg-gray-900 border border-white/10">
            <p className="text-sm text-gray-300">{artifact.originalSpec}</p>
          </div>
        </div>

        {/* Navigation Config */}
        <div>
          <h4 className="text-xs font-medium text-gray-400 uppercase mb-3">Navigation Routes</h4>
          <div className="space-y-2">
            {navigation.onSuccess && (
              <div className="flex items-center gap-2">
                <span className="text-xs px-2 py-0.5 rounded bg-green-500/20 text-green-400">Success</span>
                <span className="text-gray-300 font-mono text-sm">{navigation.onSuccess}</span>
              </div>
            )}
            {navigation.onCancel && (
              <div className="flex items-center gap-2">
                <span className="text-xs px-2 py-0.5 rounded bg-yellow-500/20 text-yellow-400">Cancel</span>
                <span className="text-gray-300 font-mono text-sm">{navigation.onCancel}</span>
              </div>
            )}
            {navigation.onError && (
              <div className="flex items-center gap-2">
                <span className="text-xs px-2 py-0.5 rounded bg-red-500/20 text-red-400">Error</span>
                <span className="text-gray-300 font-mono text-sm">{navigation.onError}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function SandboxContent() {
  const [activeTab, setActiveTab] = useState<PanelTab>('actions');
  const [fullscreen, setFullscreen] = useState(false);
  const { isRunning } = useSandbox();

  const tabs = [
    { id: 'actions' as const, label: 'Actions', icon: <Clock className="w-4 h-4" /> },
    { id: 'api' as const, label: 'API Docs', icon: <FileJson className="w-4 h-4" /> },
    { id: 'data' as const, label: 'Mock Data', icon: <Database className="w-4 h-4" /> },
    { id: 'info' as const, label: 'Info', icon: <Info className="w-4 h-4" /> },
  ];

  return (
    <div className="flex-1 flex overflow-hidden">
      {/* Artifact Preview */}
      <div className={`flex-1 flex flex-col border-r border-white/10 ${fullscreen ? 'hidden' : ''}`}>
        <div className="flex items-center justify-between px-4 py-2 border-b border-white/10 bg-white/5">
          <span className="text-sm text-gray-400">Artifact Preview</span>
          <button
            onClick={() => setFullscreen(true)}
            className="p-1.5 rounded hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
          >
            <Maximize2 className="w-4 h-4" />
          </button>
        </div>
        <div className="flex-1 overflow-auto bg-brand-bg">
          {!isRunning && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10 pointer-events-none">
              <div className="text-center">
                <Play className="w-12 h-12 text-gray-500 mx-auto mb-2" />
                <p className="text-gray-400">Start the sandbox to interact</p>
              </div>
            </div>
          )}
          <DemoOrderForm />
        </div>
      </div>

      {/* Side Panel */}
      <div className={`w-96 flex flex-col bg-brand-bg-elevated ${fullscreen ? 'flex-1' : ''}`}>
        {fullscreen && (
          <div className="flex items-center justify-between px-4 py-2 border-b border-white/10 bg-white/5">
            <span className="text-sm text-gray-400">Sandbox Panel</span>
            <button
              onClick={() => setFullscreen(false)}
              className="p-1.5 rounded hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
            >
              <Minimize2 className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Tabs */}
        <div className="flex border-b border-white/10">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
                activeTab === tab.id
                  ? 'text-brand border-b-2 border-brand bg-brand-deep/10'
                  : 'text-gray-400 hover:text-white hover:bg-white/5'
              }`}
            >
              {tab.icon}
              <span className="hidden lg:inline">{tab.label}</span>
            </button>
          ))}
        </div>

        {/* Tab Content */}
        <div className="flex-1 overflow-hidden">
          {activeTab === 'actions' && <ActionLogPanel />}
          {activeTab === 'api' && <ApiDocsPanel />}
          {activeTab === 'data' && <MockDataEditor />}
          {activeTab === 'info' && <InfoPanel />}
        </div>
      </div>
    </div>
  );
}

export function SandboxViewer({ config }: { config?: WeftConfig }) {
  const sandboxConfig = config || DEMO_CONFIG;

  return (
    <WeftSandboxProvider initialConfig={sandboxConfig}>
      <div className="h-[calc(100vh-8rem)] flex flex-col rounded-2xl overflow-hidden border border-white/10 bg-brand-bg">
        <SandboxControls />
        <SandboxContent />
      </div>
    </WeftSandboxProvider>
  );
}
