"use client";

import React, { useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { formatCurrency } from "@/lib/currency";
import { cn } from "@/lib/utils";
import { X, Plus } from "lucide-react";

/** Minimal part shape for the overlay; compatible with builder Component type */
export interface PartSelectorPart {
  id: string;
  name: string;
  price: number;
  image?: string | null;
  category: string;
  retailer?: { name: string; address?: string | null } | null;
  brand?: string;
  /** Optional specs for display (e.g. Socket, Total Cores, Boost Clock) */
  specifications?: Record<string, string | number | boolean | null | undefined>;
}

export interface PartSelectorOverlayProps {
  /** Whether the overlay is visible */
  open: boolean;
  /** Called when the overlay should close (e.g. close button, escape) */
  onClose: () => void;
  /** Title shown in the overlay header (e.g. "Processors - Quick Add") */
  title: string;
  /** List of parts to display in the grid */
  parts: PartSelectorPart[];
  /** Number of parts currently in the build (for Part List display) */
  selectedPartCount: number;
  /** Total build price to show in the sidebar */
  totalBuildPrice: number;
  /** Whether the compatibility filter is enabled */
  compatibilityChecked: boolean;
  /** Called when the compatibility toggle changes */
  onCompatibilityChange: (checked: boolean) => void;
  /** Called when user clicks "Add to build" on a part */
  onAddToBuild: (part: PartSelectorPart) => void;
  /** Optional class for the overlay container */
  className?: string;
}

/**
 * Fullscreen overlay part selector (PCPartPicker-style).
 * - Fullscreen (w-screen h-screen), disables background scroll
 * - Left sidebar: Part List, total price, Compatibility toggle
 * - Right: responsive product grid (1–4 columns) with independent scroll
 * - Responsive: sidebar stacks on mobile
 */
export function PartSelectorOverlay({
  open,
  onClose,
  title,
  parts,
  selectedPartCount,
  totalBuildPrice,
  compatibilityChecked,
  onCompatibilityChange,
  onAddToBuild,
  className,
}: PartSelectorOverlayProps) {
  // Disable background scrolling when overlay is open
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  // Escape to close
  useEffect(() => {
    if (!open) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      className={cn(
        "fixed inset-0 z-50 w-screen h-screen flex flex-col bg-slate-50 dark:bg-slate-950",
        className
      )}
      role="dialog"
      aria-modal="true"
      aria-labelledby="part-selector-title"
    >
      {/* Header: title + close */}
      <header className="flex-shrink-0 flex items-center justify-between gap-4 px-4 py-3 border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900">
        <h1 id="part-selector-title" className="text-lg font-semibold text-slate-900 dark:text-white truncate">
          {title}
        </h1>
        <Button
          variant="ghost"
          size="icon"
          onClick={onClose}
          className="flex-shrink-0 rounded-full"
          aria-label="Close"
        >
          <X className="h-5 w-5" />
        </Button>
      </header>

      {/* Split view: sidebar + main */}
      <div className="flex-1 min-h-0 flex flex-col md:flex-row overflow-hidden">
        {/* Left sidebar — fixed width on desktop, full width on mobile */}
        <aside className="flex-shrink-0 w-full md:w-64 lg:w-72 border-b md:border-b-0 md:border-r border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-4 overflow-y-auto">
          <div className="space-y-4">
            <Card className="border-slate-200 dark:border-slate-800">
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-semibold text-slate-700 dark:text-slate-300">
                  Part List
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                <div>
                  <p className="text-slate-600 dark:text-slate-400">Parts</p>
                  <p className="font-medium text-slate-900 dark:text-white">{selectedPartCount}</p>
                </div>
                <div>
                  <p className="text-slate-600 dark:text-slate-400">Total build price</p>
                  <p className="font-semibold text-green-600 dark:text-green-400">
                    {formatCurrency(totalBuildPrice)}
                  </p>
                </div>
              </CardContent>
            </Card>
            <div className="flex items-center gap-2 p-3 rounded-lg border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-800/50">
              <Checkbox
                id="overlay-compatibility"
                checked={compatibilityChecked}
                onCheckedChange={(c) => onCompatibilityChange(!!c)}
              />
              <label
                htmlFor="overlay-compatibility"
                className="text-sm font-medium text-slate-700 dark:text-slate-300 cursor-pointer"
              >
                Compatibility
              </label>
            </div>
          </div>
        </aside>

        {/* Right main: product grid with independent scroll */}
        <main className="flex-1 min-w-0 min-h-0 overflow-auto p-4 md:p-6">
          {parts.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-slate-500 dark:text-slate-400">
              <p className="text-sm">No parts in this category.</p>
            </div>
          ) : (
            <div
              className="grid gap-4 w-full"
              style={{
                gridTemplateColumns: "repeat(auto-fill, minmax(min(100%, 260px), 1fr))",
              }}
            >
              {parts.map((part) => {
                const specEntries = part.specifications
                  ? Object.entries(part.specifications).filter(([_, v]) => v != null && v !== "").slice(0, 4)
                  : [];
                return (
                  <Card
                    key={part.id}
                    className="overflow-hidden border-slate-200 dark:border-slate-800 hover:shadow-md transition-shadow flex flex-col"
                  >
                    <div className="aspect-square w-full bg-white dark:bg-slate-800 flex items-center justify-center overflow-hidden border-b border-slate-200 dark:border-slate-800">
                      <img
                        src={part.image || "/placeholder.svg"}
                        alt={part.name}
                        className="w-full h-full object-contain p-3"
                      />
                    </div>
                    <CardContent className="p-4 flex flex-col flex-1">
                      <h3 className="font-semibold text-slate-900 dark:text-white text-sm leading-snug break-words">
                        {part.name}
                      </h3>
                      <p className="text-base font-semibold text-green-600 dark:text-green-400 mt-2">
                        {formatCurrency(part.price)}
                      </p>
                      {specEntries.length > 0 && (
                        <ul className="mt-2 space-y-1 text-xs text-slate-600 dark:text-slate-400">
                          {specEntries.map(([key, value]) => (
                            <li key={key} className="break-words">
                              <span className="font-medium">{key}:</span> {String(value)}
                            </li>
                          ))}
                        </ul>
                      )}
                      <p className="text-xs text-slate-600 dark:text-slate-400 mt-1">
                        Category: {part.category}
                      </p>
                      {part.retailer?.name && (
                        <p className="text-xs text-slate-500 dark:text-slate-500 mt-0.5 truncate" title={part.retailer.name}>
                          Retailer: {part.retailer.name}
                        </p>
                      )}
                      <Button
                        className="mt-auto w-full mt-4"
                        size="sm"
                        onClick={() => onAddToBuild(part)}
                      >
                        <Plus className="h-4 w-4 mr-2" />
                        Add to build
                      </Button>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
