import { useState, useCallback, memo } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import {
  ArrowsLeftRight,
  Copy,
  CheckCircle,
  Warning,
  X,
} from '@phosphor-icons/react';
import { PlatformSelector } from './PlatformSelector';
import { LoadingSpinner } from './ui/loading-spinner';
import {
  translateCode,
  TranslationRequest,
  TranslationResult,
} from '@/lib/translation-engine';
import { PlatformId, getPlatform } from '@/lib/platforms';
import { toast } from 'sonner';

interface TranslationPanelProps {
  isOpen: boolean;
  onClose: () => void;
  currentCode: string;
  currentPlatform: PlatformId;
}

export const TranslationPanel = memo(function TranslationPanel({
  isOpen,
  onClose,
  currentCode,
  currentPlatform,
}: TranslationPanelProps) {
  const [targetPlatform, setTargetPlatform] = useState<PlatformId>('uefn');
  const [isTranslating, setIsTranslating] = useState(false);
  const [result, setResult] = useState<TranslationResult | null>(null);
  const [copied, setCopied] = useState(false);

  const handleTranslate = useCallback(async () => {
    if (!currentCode || currentCode.trim() === '') {
      toast.error('No code to translate');
      return;
    }

    setIsTranslating(true);
    setResult(null);

    const request: TranslationRequest = {
      sourceCode: currentCode,
      sourcePlatform: currentPlatform,
      targetPlatform,
    };

    const translationResult = await translateCode(request);
    setResult(translationResult);
    setIsTranslating(false);
  }, [currentCode, currentPlatform, targetPlatform]);

  const handleCopy = useCallback(async () => {
    if (result?.translatedCode) {
      await navigator.clipboard.writeText(result.translatedCode);
      setCopied(true);
      toast.success('Translated code copied to clipboard');
      setTimeout(() => setCopied(false), 2000);
    }
  }, [result]);

  const sourcePlatform = getPlatform(currentPlatform);
  const targetPlatformInfo = getPlatform(targetPlatform);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-card border border-border rounded-lg shadow-2xl w-full max-w-6xl h-[80vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-border">
          <div className="flex items-center gap-3">
            <ArrowsLeftRight size={24} weight="bold" className="text-accent" />
            <div>
              <h2 className="text-lg font-bold">Cross-Platform Translation</h2>
              <p className="text-xs text-muted-foreground">
                Translate your code between game platforms
              </p>
            </div>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            className="h-8 w-8 p-0"
          >
            <X size={20} />
          </Button>
        </div>

        {/* Platform Selection */}
        <div className="flex items-center justify-center gap-4 px-6 py-4 border-b border-border bg-muted/20">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">Source:</span>
            <Badge
              variant="outline"
              className="flex items-center gap-2"
              style={{ borderColor: sourcePlatform.color }}
            >
              <span>{sourcePlatform.icon}</span>
              <span>{sourcePlatform.displayName}</span>
            </Badge>
          </div>
          <ArrowsLeftRight size={20} className="text-muted-foreground" />
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">Target:</span>
            <PlatformSelector
              value={targetPlatform}
              onChange={setTargetPlatform}
              disabled={isTranslating}
            />
          </div>
          <Button
            onClick={handleTranslate}
            disabled={
              isTranslating ||
              !currentCode ||
              currentPlatform === targetPlatform
            }
            className="ml-4"
          >
            {isTranslating ? (
              <>
                <LoadingSpinner />
                <span className="ml-2">Translating...</span>
              </>
            ) : (
              <>
                <ArrowsLeftRight size={16} className="mr-2" />
                Translate
              </>
            )}
          </Button>
        </div>

        {/* Side-by-Side Code View */}
        <div className="flex-1 flex overflow-hidden">
          {/* Source Code */}
          <div className="flex-1 flex flex-col border-r border-border">
            <div className="px-4 py-2 bg-muted/30 border-b border-border">
              <h3 className="text-sm font-semibold flex items-center gap-2">
                <span>{sourcePlatform.icon}</span>
                {sourcePlatform.language} (Original)
              </h3>
            </div>
            <ScrollArea className="flex-1">
              <pre className="p-4 text-xs font-mono leading-relaxed">
                {currentCode || '// No code to translate'}
              </pre>
            </ScrollArea>
          </div>

          {/* Translated Code */}
          <div className="flex-1 flex flex-col">
            <div className="px-4 py-2 bg-muted/30 border-b border-border flex items-center justify-between">
              <h3 className="text-sm font-semibold flex items-center gap-2">
                <span>{targetPlatformInfo.icon}</span>
                {targetPlatformInfo.language} (Translated)
              </h3>
              {result?.translatedCode && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleCopy}
                  className="h-7 text-xs"
                >
                  {copied ? (
                    <>
                      <CheckCircle size={14} className="mr-1" />
                      Copied
                    </>
                  ) : (
                    <>
                      <Copy size={14} className="mr-1" />
                      Copy
                    </>
                  )}
                </Button>
              )}
            </div>
            <ScrollArea className="flex-1">
              {isTranslating ? (
                <div className="h-full flex items-center justify-center">
                  <div className="text-center">
                    <LoadingSpinner />
                    <p className="text-sm text-muted-foreground mt-4">
                      Translating code...
                    </p>
                  </div>
                </div>
              ) : result ? (
                <div className="p-4 space-y-4">
                  {result.success && result.translatedCode ? (
                    <>
                      <pre className="text-xs font-mono leading-relaxed bg-muted/30 p-3 rounded-md border border-border">
                        {result.translatedCode}
                      </pre>

                      {result.explanation && (
                        <div className="bg-blue-500/10 border border-blue-500/30 rounded-md p-3">
                          <h4 className="text-xs font-semibold flex items-center gap-2 mb-2">
                            <CheckCircle size={14} className="text-blue-500" />
                            Explanation
                          </h4>
                          <p className="text-xs text-muted-foreground">
                            {result.explanation}
                          </p>
                        </div>
                      )}

                      {result.warnings && result.warnings.length > 0 && (
                        <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-md p-3">
                          <h4 className="text-xs font-semibold flex items-center gap-2 mb-2">
                            <Warning size={14} className="text-yellow-500" />
                            Warnings
                          </h4>
                          <ul className="text-xs text-muted-foreground space-y-1">
                            {result.warnings.map((warning, i) => (
                              <li key={i}>• {warning}</li>
                            ))}
                          </ul>
                        </div>
                      )}
                    </>
                  ) : (
                    <div className="bg-red-500/10 border border-red-500/30 rounded-md p-4 text-center">
                      <p className="text-sm text-red-500">
                        {result.error || 'Translation failed'}
                      </p>
                    </div>
                  )}
                </div>
              ) : (
                <div className="h-full flex items-center justify-center">
                  <div className="text-center text-muted-foreground">
                    <ArrowsLeftRight size={48} className="mx-auto mb-4 opacity-50" />
                    <p className="text-sm">
                      Click "Translate" to convert your code
                    </p>
                    <p className="text-xs mt-2">
                      {sourcePlatform.displayName} → {targetPlatformInfo.displayName}
                    </p>
                  </div>
                </div>
              )}
            </ScrollArea>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-3 border-t border-border bg-muted/20">
          <p className="text-xs text-muted-foreground text-center">
            🚀 Cross-platform translation powered by AeThex Studio AI • Support
            for {sourcePlatform.displayName}, {targetPlatformInfo.displayName},
            and more coming soon
          </p>
        </div>
      </div>
    </div>
  );
});
