'use client';

import { motion, AnimatePresence } from 'framer-motion';
import {
  MousePointerClick,
  FormInput,
  Send,
  Globe,
  Navigation,
  Hand,
  ListFilter,
  Download,
  Trash2,
  Clock,
  ArrowRight,
} from 'lucide-react';
import { useSandbox } from './sandbox-context';
import { ActionLog } from '@/lib/weft';

const ACTION_ICONS: Record<ActionLog['actionType'], React.ReactNode> = {
  CLICK: <MousePointerClick className="w-4 h-4" />,
  INPUT: <FormInput className="w-4 h-4" />,
  SUBMIT: <Send className="w-4 h-4" />,
  API_CALL: <Globe className="w-4 h-4" />,
  NAVIGATE: <Navigation className="w-4 h-4" />,
  SELECT: <ListFilter className="w-4 h-4" />,
  HOVER: <Hand className="w-4 h-4" />,
};

const ACTION_COLORS: Record<ActionLog['actionType'], string> = {
  CLICK: 'text-blue-400',
  INPUT: 'text-brand-secondary-light',
  SUBMIT: 'text-green-400',
  API_CALL: 'text-brand',
  NAVIGATE: 'text-yellow-400',
  SELECT: 'text-pink-400',
  HOVER: 'text-gray-400',
};

function formatTime(date: Date): string {
  return date.toISOString().split('T')[1].split('.')[0];
}

function ActionItem({ action }: { action: ActionLog }) {
  const getDetails = () => {
    switch (action.actionType) {
      case 'API_CALL':
        return (
          <span className="flex items-center gap-1">
            <span className={`px-1.5 py-0.5 rounded text-xs font-mono ${getMethodColor(action.wouldTrigger.method as string)}`}>
              {action.wouldTrigger.method}
            </span>
            <span className="text-gray-300">{action.wouldTrigger.endpoint}</span>
            {action.duration && <span className="text-gray-500 text-xs">({action.duration}ms)</span>}
          </span>
        );
      case 'CLICK':
        return (
          <span className="flex items-center gap-1">
            <span className="text-gray-300">{action.element.text || action.element.selector}</span>
            {action.wouldTrigger.navigation && (
              <span className="flex items-center text-yellow-400 text-xs">
                <ArrowRight className="w-3 h-3 mx-1" />
                {action.wouldTrigger.navigation}
              </span>
            )}
          </span>
        );
      case 'INPUT':
      case 'SELECT':
        return (
          <span className="flex items-center gap-1">
            <span className="text-gray-400">{action.element.selector}:</span>
            <span className="text-white font-mono text-xs bg-white/10 px-1.5 py-0.5 rounded">
              {String(action.element.value)}
            </span>
          </span>
        );
      case 'SUBMIT':
        return (
          <span className="flex items-center gap-1">
            <ArrowRight className="w-3 h-3 text-gray-500" />
            <span className={`px-1.5 py-0.5 rounded text-xs font-mono ${getMethodColor(action.wouldTrigger.method as string)}`}>
              {action.wouldTrigger.method}
            </span>
            <span className="text-gray-300">{action.wouldTrigger.endpoint}</span>
          </span>
        );
      default:
        return <span className="text-gray-400">{action.element.selector}</span>;
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, x: -10 }}
      animate={{ opacity: 1, x: 0 }}
      exit={{ opacity: 0, x: 10 }}
      className="flex items-start gap-3 p-3 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 transition-colors"
    >
      <div className={`mt-0.5 ${ACTION_COLORS[action.actionType]}`}>
        {ACTION_ICONS[action.actionType]}
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-1">
          <span className={`text-xs font-medium uppercase ${ACTION_COLORS[action.actionType]}`}>
            {action.actionType.replace('_', ' ')}
          </span>
          <span className="text-xs text-gray-500 flex items-center gap-1">
            <Clock className="w-3 h-3" />
            {formatTime(action.timestamp)}
          </span>
        </div>
        <div className="text-sm truncate">{getDetails()}</div>
      </div>
    </motion.div>
  );
}

function getMethodColor(method: string): string {
  switch (method) {
    case 'GET': return 'bg-green-500/20 text-green-400';
    case 'POST': return 'bg-blue-500/20 text-blue-400';
    case 'PUT': return 'bg-yellow-500/20 text-yellow-400';
    case 'PATCH': return 'bg-orange-500/20 text-orange-400';
    case 'DELETE': return 'bg-red-500/20 text-red-400';
    default: return 'bg-gray-500/20 text-gray-400';
  }
}

export function ActionLogPanel() {
  const { actionLogs, summary, clearActions, sandbox } = useSandbox();

  const handleExport = () => {
    if (sandbox) {
      const text = sandbox.exportActionsAsText();
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'weft-action-log.txt';
      a.click();
      URL.revokeObjectURL(url);
    }
  };

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-white/10">
        <h3 className="font-semibold text-white flex items-center gap-2">
          <Clock className="w-5 h-5 text-brand" />
          Action Log
          {actionLogs.length > 0 && (
            <span className="text-xs bg-brand-deep/20 text-brand px-2 py-0.5 rounded-full">
              {actionLogs.length}
            </span>
          )}
        </h3>
        <div className="flex items-center gap-2">
          <button
            onClick={handleExport}
            disabled={actionLogs.length === 0}
            className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            title="Export log"
          >
            <Download className="w-4 h-4" />
          </button>
          <button
            onClick={clearActions}
            disabled={actionLogs.length === 0}
            className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-red-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            title="Clear log"
          >
            <Trash2 className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Summary */}
      {summary && summary.totalActions > 0 && (
        <div className="px-4 py-2 border-b border-white/10 bg-white/5">
          <div className="flex items-center gap-4 text-xs text-gray-400">
            {Object.entries(summary.byType).map(([type, count]) => (
              <span key={type} className="flex items-center gap-1">
                <span className={ACTION_COLORS[type as ActionLog['actionType']]}>
                  {ACTION_ICONS[type as ActionLog['actionType']]}
                </span>
                {count}
              </span>
            ))}
            {summary.averageApiLatency > 0 && (
              <span className="ml-auto">Avg: {summary.averageApiLatency}ms</span>
            )}
          </div>
        </div>
      )}

      {/* Log List */}
      <div className="flex-1 overflow-y-auto p-4 space-y-2">
        <AnimatePresence mode="popLayout">
          {actionLogs.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="text-center py-12 text-gray-500"
            >
              <Clock className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>No actions recorded yet</p>
              <p className="text-sm mt-1">Interact with the sandbox to see logs</p>
            </motion.div>
          ) : (
            [...actionLogs].reverse().map((action) => (
              <ActionItem key={action.id} action={action} />
            ))
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
