/**
 * Layout Engine Component
 *
 * Allows users to arrange panels into comic pages using layout templates
 */

import type { JSX } from "react";
import { useState, useCallback, useMemo } from "react";
import {
  LayoutGrid,
  RefreshCw,
  AlertCircle,
  Check,
  ChevronLeft,
  ChevronRight,
  Grid3X3,
  Maximize,
  Settings,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useComicStore } from "@/store/comicStore";
import {
  LAYOUT_PATTERNS,
  PAGE_SIZES,
  autoLayoutPages,
} from "@/utils/layoutPatterns";
import type { LayoutPattern, PageLayout } from "@/types";

interface LayoutTemplateCardProps {
  pattern: LayoutPattern;
  isSelected: boolean;
  onClick: () => void;
}

function LayoutTemplateCard({
  pattern,
  isSelected,
  onClick,
}: LayoutTemplateCardProps): JSX.Element {
  return (
    <button
      onClick={onClick}
      className={`p-4 border rounded-lg text-left transition-all hover:border-primary ${
        isSelected ? "border-primary bg-primary/5 ring-1 ring-primary" : "bg-card"
      }`}
    >
      <div className="flex items-start justify-between mb-2">
        <h4 className="font-semibold">{pattern.name}</h4>
        {isSelected && <Check className="w-4 h-4 text-primary" />}
      </div>
      <p className="text-sm text-muted-foreground mb-3">
        {pattern.description}
      </p>
      <div className="flex items-center gap-2 text-xs text-muted-foreground">
        <Grid3X3 className="w-3 h-3" />
        <span>Up to {pattern.maxPanels} panels</span>
      </div>
      {/* Visual preview of layout */}
      <div className="mt-3 aspect-[3/4] bg-muted rounded relative overflow-hidden">
        {pattern.cells.map((cell, i) => (
          <div
            key={i}
            className="absolute bg-primary/20 border border-primary/30 rounded-sm"
            style={{
              left: `${cell.x * 100}%`,
              top: `${cell.y * 100}%`,
              width: `${cell.w * 100}%`,
              height: `${cell.h * 100}%`,
            }}
          />
        ))}
      </div>
    </button>
  );
}

interface PagePreviewProps {
  pageLayout: PageLayout;
  panelImages: Record<string, { url: string }>;
  pageNumber: number;
  isSelected: boolean;
  onClick: () => void;
}

function PagePreview({
  pageLayout,
  panelImages,
  pageNumber,
  isSelected,
  onClick,
}: PagePreviewProps): JSX.Element {
  return (
    <button
      onClick={onClick}
      className={`border rounded-lg overflow-hidden transition-all hover:border-primary ${
        isSelected ? "border-primary ring-1 ring-primary" : "bg-card"
      }`}
    >
      {/* Page Header */}
      <div className="px-3 py-2 border-b bg-muted/30 flex items-center justify-between">
        <span className="font-medium">Page {pageNumber}</span>
        <span className="text-xs text-muted-foreground">
          {pageLayout.panels.length} panels
        </span>
      </div>

      {/* Page Preview */}
      <div className="aspect-[3/4] bg-white relative">
        {pageLayout.panels.map((panel) => {
          const image = panelImages[panel.panelId];

          return (
            <div
              key={panel.panelId}
              className="absolute border border-gray-300 bg-gray-50 overflow-hidden"
              style={{
                left: `${panel.layoutCell.x * 100}%`,
                top: `${panel.layoutCell.y * 100}%`,
                width: `${panel.layoutCell.w * 100}%`,
                height: `${panel.layoutCell.h * 100}%`,
              }}
            >
              {image ? (
                <img
                  src={image.url}
                  alt={`Panel ${panel.panelNumber}`}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-xs text-gray-400">
                  {panel.panelNumber}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Pattern Name */}
      <div className="px-3 py-2 border-t text-xs text-muted-foreground text-center">
        {pageLayout.pattern.name}
      </div>
    </button>
  );
}

export function LayoutEngine(): JSX.Element {
  const {
    script,
    panelImages,
    pageLayouts,
    setPageLayouts,
    pageSize,
    setPageSize,
    artStyle,
    setWorkflowStep,
    workflow,
  } = useComicStore();

  const [selectedPattern, setSelectedPattern] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(0);

  // Get all panels from script
  const allPanels = useMemo(() => {
    if (!script) return [];
    return script.pages.flatMap((page, pageIdx) =>
      page.panels.map((panel) => ({
        panelId: panel.panelId,
        panelNumber: panel.panelNumber,
        pageNumber: pageIdx + 1,
      }))
    );
  }, [script]);

  const hasLayouts = pageLayouts.length > 0;

  const handleAutoLayout = useCallback(() => {
    if (allPanels.length === 0) return;

    const size = PAGE_SIZES[pageSize];
    const layouts = autoLayoutPages(
      allPanels,
      size,
      artStyle,
      selectedPattern || undefined
    );

    setPageLayouts(layouts);
  }, [allPanels, pageSize, artStyle, selectedPattern, setPageLayouts]);

  const handlePatternSelect = useCallback(
    (patternId: string) => {
      setSelectedPattern(patternId);

      // If we have panels, auto-apply layout with this pattern
      if (allPanels.length > 0 && !hasLayouts) {
        const pattern = LAYOUT_PATTERNS.find((p) => p.id === patternId);
        if (pattern) {
          const size = PAGE_SIZES[pageSize];
          const layouts = autoLayoutPages(allPanels, size, artStyle, patternId);
          setPageLayouts(layouts);
        }
      }
    },
    [allPanels, pageSize, artStyle, hasLayouts, setPageLayouts]
  );

  const handleProceed = useCallback(() => {
    setWorkflowStep("speech-bubbles");
  }, [setWorkflowStep]);

  const handleClearLayouts = useCallback(() => {
    setPageLayouts([]);
    setSelectedPattern(null);
  }, [setPageLayouts]);

  if (!script) {
    return (
      <div className="flex items-center justify-center h-full">
        <p className="text-muted-foreground">
          No script available. Generate a script and panels first.
        </p>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold flex items-center gap-2">
            <LayoutGrid className="w-6 h-6" />
            Page Layout
          </h2>
          <p className="text-muted-foreground">
            {hasLayouts
              ? `${pageLayouts.length} pages created with ${allPanels.length} panels`
              : `${allPanels.length} panels ready to layout`}
          </p>
        </div>

        <div className="flex gap-2">
          {hasLayouts && (
            <Button variant="outline" onClick={handleClearLayouts}>
              <RefreshCw className="w-4 h-4 mr-2" />
              Redo Layout
            </Button>
          )}
          <Button onClick={handleProceed} disabled={!hasLayouts}>
            {hasLayouts ? "Proceed to Speech Bubbles" : "Create Layout First"}
          </Button>
        </div>
      </div>

      {/* Error Display */}
      {workflow.error && (
        <div className="bg-destructive/10 border border-destructive/30 text-destructive px-4 py-3 rounded-lg flex items-center gap-3">
          <AlertCircle className="w-5 h-5 shrink-0" />
          <p className="text-sm">{workflow.error}</p>
        </div>
      )}

      {/* Layout Options */}
      {!hasLayouts && (
        <div className="space-y-6">
          {/* Page Size Selector */}
          <div className="bg-muted/50 p-4 rounded-lg border">
            <div className="flex items-center gap-2 mb-4">
              <Maximize className="w-4 h-4" />
              <h3 className="font-semibold">Page Size</h3>
            </div>
            <div className="flex flex-wrap gap-2">
              {Object.entries(PAGE_SIZES).map(([key, size]) => (
                <button
                  key={key}
                  onClick={() => setPageSize(key as 'a4' | 'letter' | 'manga' | 'webtoon' | 'square')}
                  className={`px-3 py-2 rounded-lg border text-sm transition-colors ${
                    pageSize === key
                      ? "border-primary bg-primary/10 text-primary"
                      : "bg-background hover:bg-muted"
                  }`}
                >
                  {size.name}
                </button>
              ))}
            </div>
          </div>

          {/* Layout Pattern Selector */}
          <div>
            <div className="flex items-center gap-2 mb-4">
              <Settings className="w-4 h-4" />
              <h3 className="font-semibold">Choose Layout Pattern</h3>
              <span className="text-sm text-muted-foreground">
                (Optional - auto-selected based on panel count)
              </span>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              {LAYOUT_PATTERNS.map((pattern) => (
                <LayoutTemplateCard
                  key={pattern.id}
                  pattern={pattern}
                  isSelected={selectedPattern === pattern.id}
                  onClick={() => handlePatternSelect(pattern.id)}
                />
              ))}
            </div>
          </div>

          {/* Auto Layout Button */}
          <div className="flex justify-center">
            <Button
              size="lg"
              onClick={handleAutoLayout}
              disabled={allPanels.length === 0}
            >
              <LayoutGrid className="w-4 h-4 mr-2" />
              Auto-Layout Pages
            </Button>
          </div>
        </div>
      )}

      {/* Page Previews */}
      {hasLayouts && (
        <div className="space-y-6">
          {/* Page Navigation */}
          {pageLayouts.length > 1 && (
            <div className="flex items-center justify-center gap-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
                disabled={currentPage === 0}
              >
                <ChevronLeft className="w-4 h-4" />
              </Button>
              <span className="text-sm text-muted-foreground">
                Page {currentPage + 1} of {pageLayouts.length}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() =>
                  setCurrentPage((p) =>
                    Math.min(pageLayouts.length - 1, p + 1)
                  )
                }
                disabled={currentPage === pageLayouts.length - 1}
              >
                <ChevronRight className="w-4 h-4" />
              </Button>
            </div>
          )}

          {/* Pages Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {pageLayouts.map((layout, index) => (
              <PagePreview
                key={layout.pageNumber}
                pageLayout={layout}
                panelImages={panelImages}
                pageNumber={layout.pageNumber}
                isSelected={currentPage === index}
                onClick={() => setCurrentPage(index)}
              />
            ))}
          </div>

          {/* Layout Summary */}
          <div className="bg-muted/50 p-4 rounded-lg border">
            <h3 className="font-semibold mb-2">Layout Summary</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">Total Pages:</span>
                <p className="font-medium">{pageLayouts.length}</p>
              </div>
              <div>
                <span className="text-muted-foreground">Total Panels:</span>
                <p className="font-medium">{allPanels.length}</p>
              </div>
              <div>
                <span className="text-muted-foreground">Page Size:</span>
                <p className="font-medium">{PAGE_SIZES[pageSize].name}</p>
              </div>
              <div>
                <span className="text-muted-foreground">Dimensions:</span>
                <p className="font-medium">
                  {PAGE_SIZES[pageSize].width} × {PAGE_SIZES[pageSize].height}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
