import { PageLayout } from "@/components/layout/PageLayout";
import { useParams } from "wouter";
import { useQuery } from "@tanstack/react-query";
import { Work, Translation } from "@shared/schema";
import { LineNumberedText } from "@/components/reading/LineNumberedText";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Maximize2, Minimize2 } from "lucide-react";
import { useReadingSettings } from "@/hooks/use-reading-settings";
import { Link } from "wouter";
import { Skeleton } from "@/components/ui/skeleton";

export default function WorkCompare() {
  const { slug, translationId } = useParams();
  const { settings, toggleZenMode } = useReadingSettings();
  const [selectedTranslationId, setSelectedTranslationId] = useState<number>(
    parseInt(translationId || "0", 10)
  );
  const [highlightedLine, setHighlightedLine] = useState<number | null>(null);

  const { data: work, isLoading: workLoading } = useQuery<Work>({
    queryKey: [`/api/works/${slug}`],
  });

  const { data: translations, isLoading: translationsLoading } = useQuery<Translation[]>({
    queryKey: [`/api/works/${slug}/translations`],
    enabled: !!work,
  });

  const { data: selectedTranslation, isLoading: translationLoading } = useQuery<Translation>({
    queryKey: [`/api/translations/${selectedTranslationId}`],
    enabled: !!selectedTranslationId,
  });

  const handleLineClick = (lineNumber: number) => {
    setHighlightedLine(lineNumber);
    
    // Scroll the corresponding line in the other panel into view
    const otherPanelElement = document.getElementById(`line-${lineNumber}-other`);
    if (otherPanelElement) {
      otherPanelElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  };

  if (workLoading || translationsLoading || translationLoading) {
    return (
      <PageLayout>
        <div className="max-w-[var(--content-width)] mx-auto px-4 py-8">
          <Skeleton className="h-12 w-3/4 mb-8" />
          <div className="flex flex-col md:flex-row gap-8">
            <div className="flex-1">
              <Skeleton className="h-8 w-1/2 mb-4" />
              <div className="space-y-2">
                {Array.from({ length: 8 }).map((_, i) => (
                  <Skeleton key={i} className="h-6" />
                ))}
              </div>
            </div>
            <div className="flex-1">
              <Skeleton className="h-8 w-1/2 mb-4" />
              <div className="space-y-2">
                {Array.from({ length: 8 }).map((_, i) => (
                  <Skeleton key={i} className="h-6" />
                ))}
              </div>
            </div>
          </div>
        </div>
      </PageLayout>
    );
  }

  if (!work || !translations || !selectedTranslation) {
    return (
      <PageLayout>
        <div className="max-w-[var(--content-width)] mx-auto px-4 py-16 text-center">
          <h1 className="text-2xl font-bold mb-4">Content not found</h1>
          <p className="mb-6">The work or translation you're looking for could not be found.</p>
          <Link href="/explore">
            <Button>Explore Works</Button>
          </Link>
        </div>
      </PageLayout>
    );
  }

  return (
    <PageLayout zenMode={settings.zenMode}>
      <div className={`compare-view ${settings.zenMode ? 'zen-mode' : ''}`}>
        <div className="sticky top-16 z-10 bg-cream dark:bg-dark-bg border-b border-sage/20 dark:border-sage/10 shadow-sm">
          <div className="max-w-[var(--content-width)] mx-auto px-4 md:px-6 py-3">
            <div className="flex items-center justify-between">
              <h1 className="text-xl font-bold font-serif text-navy dark:text-cream">
                {work.title} <span className="text-navy/60 dark:text-cream/60 font-normal text-base">— Translation Comparison</span>
              </h1>
              <div className="flex gap-2">
                <Button
                  variant="ghost"
                  size="icon"
                  className="btn-feedback p-2 rounded-full text-navy/70 dark:text-cream/70 hover:bg-navy/10 dark:hover:bg-cream/10"
                  onClick={toggleZenMode}
                >
                  {settings.zenMode ? (
                    <Minimize2 className="h-5 w-5" />
                  ) : (
                    <Maximize2 className="h-5 w-5" />
                  )}
                  <span className="sr-only">{settings.zenMode ? 'Exit zen mode' : 'Zen mode'}</span>
                </Button>
                
                <Link href={`/works/${slug}`}>
                  <Button 
                    variant="outline"
                    className="py-1.5 px-3 rounded-full bg-navy/10 hover:bg-navy/20 dark:bg-navy/20 dark:hover:bg-navy/30 text-navy dark:text-cream/90 font-sans text-sm transition-colors"
                  >
                    Exit Compare
                  </Button>
                </Link>
              </div>
            </div>
          </div>
        </div>

        <div className="flex flex-col md:flex-row max-w-[var(--content-width)] mx-auto px-4 md:px-6 py-6">
          {/* Left panel (original) */}
          <div className="flex-1 md:pr-6 md:border-r border-sage/20 dark:border-sage/10">
            <div className="mb-4">
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-medium font-serif text-navy dark:text-cream">{work.language} (Original)</h2>
                  <p className="text-sm text-navy/70 dark:text-cream/70">
                    {work.author?.name || 'Unknown author'}, {work.year || 'Unknown year'}
                  </p>
                </div>
              </div>
            </div>
            <LineNumberedText 
              content={work.content}
              fontSizeClass={settings.fontSize}
              onLineClick={handleLineClick}
              highlightedLine={highlightedLine || undefined}
            />
          </div>

          {/* Right panel (translation) */}
          <div className="flex-1 md:pl-6 mt-8 md:mt-0">
            <div className="mb-4">
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-medium font-serif text-navy dark:text-cream">{selectedTranslation.language}</h2>
                  <p className="text-sm text-navy/70 dark:text-cream/70">
                    Translated by Translator {selectedTranslation.translatorId}, {selectedTranslation.year || 'Unknown year'}
                  </p>
                </div>
                <div>
                  <Select 
                    value={selectedTranslationId.toString()} 
                    onValueChange={(value) => setSelectedTranslationId(parseInt(value, 10))}
                  >
                    <SelectTrigger className="w-[200px]">
                      <SelectValue placeholder="Select translation" />
                    </SelectTrigger>
                    <SelectContent>
                      {translations.map(translation => (
                        <SelectItem key={translation.id} value={translation.id.toString()}>
                          {translation.language} - Translator {translation.translatorId} {translation.year ? `(${translation.year})` : ''}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
            <LineNumberedText 
              content={selectedTranslation.content}
              fontSizeClass={settings.fontSize}
              onLineClick={handleLineClick}
              highlightedLine={highlightedLine || undefined}
            />
          </div>
        </div>
      </div>
    </PageLayout>
  );
}
