'use client';

import React, { useState, useCallback, memo, useMemo } from 'react';
import { LogEntry } from '../hooks/use-logger';
import { useLoggerContext } from '../hooks/use-logger-context';

const LoggerAnimations = ({ color = '#dc2626' }: { color?: string }) => (
  <style jsx global>{`
    @keyframes pulse {
      0% {
        transform: scale(0.95);
        box-shadow: 0 0 0 0 ${color}80;
      }

      70% {
        transform: scale(1.05);
        box-shadow: 0 0 0 10px ${color}00;
      }

      100% {
        transform: scale(0.95);
        box-shadow: 0 0 0 0 ${color}00;
      }
    }
  `}</style>
);

const LogLevelColors = {
  warn: '#ff9800', // orange
  error: '#f44336' // red
};

const LoggerTrigger = memo(
  ({
    onClick,
    logCount = 0,
    currentColor
  }: {
    onClick: () => void;
    logCount?: number;
    currentColor: string;
  }) => {
    return (
      <button
        onClick={onClick}
        className="fixed bottom-4 right-4 w-14 h-14 border border-white rounded-full flex items-center justify-center shadow-lg z-[9999] hover:opacity-90 transition-colors"
        aria-label="Open Logger"
        style={{
          backgroundColor: currentColor,
          ...(logCount > 0 && {
            animation: 'pulse 2s infinite'
          })
        }}
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth="1.5"
          stroke="currentColor"
          className="text-white size-6"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"
          />
        </svg>

        {logCount > 0 && (
          <span
            className="absolute w-5 h-5 -bottom-[5px] p-1 -left-[5px] border-2 border-white rounded-full flex items-center justify-center text-[8px] text-white font-bold"
            style={{
              backgroundColor: currentColor
            }}
          >
            {logCount > 99 ? '99+' : logCount}
          </span>
        )}
      </button>
    );
  }
);

LoggerTrigger.displayName = 'LoggerTrigger';

const LogItem = memo(({ log }: { log: LogEntry }) => {
  const [expanded, setExpanded] = useState(false);
  const hasPayload = log.payload && Object.keys(log.payload).length > 0;

  const toggleExpanded = useCallback(() => {
    setExpanded((prev) => !prev);
  }, []);

  return (
    <div className="border-b border-gray-200 py-2">
      <div className="relative">
        <div
          className="absolute top-0 left-0 w-3 h-3 rounded-full mt-1.5 mr-2 flex-shrink-0"
          style={{
            backgroundColor: LogLevelColors[log.level],
            boxShadow: `0 0 5px ${LogLevelColors[log.level]}`
          }}
        />
        <div className="ml-6">
          <div className="flex justify-between">
            <span
              className="font-medium capitalize"
              style={{
                color: LogLevelColors[log.level]
              }}
            >
              {log.level}
            </span>
            <span className="text-xs text-gray-500">
              {log.timestamp.toLocaleTimeString()}
            </span>
          </div>
          <p className="text-sm">{log.message}</p>
          {hasPayload && (
            <button
              onClick={toggleExpanded}
              className="text-xs text-blue-500 mt-1 hover:text-blue-700 transition-colors"
            >
              {expanded ? 'Hide Details' : 'Show Details'}
            </button>
          )}
          {expanded && hasPayload && (
            <pre className="text-xs bg-gray-100 p-2 mt-1 rounded overflow-auto max-h-96 max-w-full">
              {JSON.stringify(log.payload, null, 2)}
            </pre>
          )}
        </div>
      </div>
    </div>
  );
});

LogItem.displayName = 'LogItem';

export const LoggerPopup = () => {
  const {
    logs,
    isVisible,
    toggleVisibility,
    clearLogs,
    isDevelopment,
    hasError,
    hasWarning
  } = useLoggerContext();

  const currentColor = useMemo(() => {
    if (logs.length === 0) return '#b5afaf';
    if (hasError) return '#dc2626';
    if (hasWarning) return '#ff9800';

    return '#b5afaf';
  }, [logs.length, hasError, hasWarning]);

  if (!isDevelopment) {
    return null;
  }

  if (!isVisible) {
    return (
      <>
        <LoggerAnimations color={currentColor} />
        <LoggerTrigger
          onClick={toggleVisibility}
          logCount={logs.length}
          currentColor={currentColor}
        />
      </>
    );
  }

  return (
    <>
      <LoggerAnimations color={currentColor} />
      <LoggerTrigger
        onClick={toggleVisibility}
        logCount={logs.length}
        currentColor={currentColor}
      />
      <div className="fixed bottom-20 right-4 w-96 max-w-[calc(100vw-2rem)] bg-white rounded-lg shadow-xl z-50 border-2 border-gray-200 max-h-[70vh] flex flex-col">
        <div className="flex items-center justify-between p-3 border-b border-gray-200">
          <h3 className="font-bold flex items-center">Development Logger</h3>
          <div className="flex space-x-2">
            <button
              onClick={clearLogs}
              className="text-xs bg-gray-200 hover:bg-gray-300 px-2 py-1 rounded transition-colors"
            >
              Clear
            </button>
            <button
              onClick={toggleVisibility}
              className="text-xs bg-gray-200 hover:bg-gray-300 px-2 py-1 rounded transition-colors"
            >
              Close
            </button>
          </div>
        </div>
        <div className="overflow-y-auto flex-grow p-3">
          {logs.length === 0 ? (
            <p className="text-gray-500 text-center py-4">No logs yet</p>
          ) : (
            logs.map((log) => <LogItem key={log.id} log={log} />)
          )}
        </div>
      </div>
    </>
  );
};
