"use client";

import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Eye, Smartphone, Monitor, Tablet } from "lucide-react";
import { LayoutData, ComponentData } from "@/types/screen";
import ContainerComponent from "./layout/ContainerComponent";
import RowComponent from "./layout/RowComponent";
import ColumnComponent from "./layout/ColumnComponent";
import WidgetFactory from "./WidgetFactory";

interface ScreenPreviewProps {
  layout: LayoutData;
  screenName: string;
  className?: string;
}

type PreviewMode = "desktop" | "tablet" | "mobile";

export default function ScreenPreview({ layout, screenName, className }: ScreenPreviewProps) {
  const [previewMode, setPreviewMode] = useState<PreviewMode>("desktop");
  const [formData, setFormData] = useState<Record<string, any>>({});

  // 미리보기 모드별 스타일
  const getPreviewStyles = (mode: PreviewMode) => {
    switch (mode) {
      case "desktop":
        return "w-full max-w-6xl mx-auto";
      case "tablet":
        return "w-full max-w-2xl mx-auto border-x-8 border-border";
      case "mobile":
        return "w-full max-w-sm mx-auto border-x-4 border-border";
      default:
        return "w-full";
    }
  };

  // 폼 데이터 변경 처리
  const handleFormChange = (fieldId: string, value: any) => {
    setFormData((prev) => ({
      ...prev,
      [fieldId]: value,
    }));
  };

  // 컴포넌트 렌더링 (미리보기용)
  const renderPreviewComponent = (component: ComponentData) => {
    const isSelected = false; // 미리보기에서는 선택 불가

    switch (component.type) {
      case "container":
        return (
          <ContainerComponent key={component.id} component={component} isSelected={isSelected} onClick={() => {}}>
            {layout.components.filter((c) => c.parentId === component.id).map(renderPreviewComponent)}
          </ContainerComponent>
        );

      case "row":
        return (
          <RowComponent key={component.id} component={component} isSelected={isSelected} onClick={() => {}}>
            {layout.components.filter((c) => c.parentId === component.id).map(renderPreviewComponent)}
          </RowComponent>
        );

      case "column":
        return (
          <ColumnComponent key={component.id} component={component} isSelected={isSelected} onClick={() => {}}>
            {layout.components.filter((c) => c.parentId === component.id).map(renderPreviewComponent)}
          </ColumnComponent>
        );

      case "widget":
        return (
          <div
            key={component.id}
            className="w-full"
            style={{
              gridColumn: `span ${component.size.width}`,
            }}
          >
            <WidgetFactory
              widget={component}
              value={formData[component.id] || ""}
              onChange={(value) => handleFormChange(component.id, value)}
            />
          </div>
        );

      default:
        return null;
    }
  };

  // 그리드 레이아웃으로 컴포넌트 배치
  const renderGridLayout = () => {
    const { gridSettings } = layout;
    const { columns, gap, padding } = gridSettings;

    return (
      <div
        className="min-h-screen bg-background"
        style={{
          padding: `${padding}px`,
        }}
      >
        <div
          className="grid gap-4"
          style={{
            gridTemplateColumns: `repeat(${columns}, 1fr)`,
            gap: `${gap}px`,
          }}
        >
          {layout.components
            .filter((c) => !c.parentId) // 최상위 컴포넌트만 렌더링
            .map(renderPreviewComponent)}
        </div>
      </div>
    );
  };

  // 폼 데이터 초기화
  const resetFormData = () => {
    setFormData({});
  };

  // 폼 데이터 출력
  const logFormData = () => {
    // console.log("폼 데이터:", formData);
  };

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 미리보기 헤더 */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <CardTitle className="flex items-center gap-2 text-sm font-medium sm:text-base">
              <Eye className="h-4 w-4" />
              {screenName} - 미리보기
            </CardTitle>
            <div className="flex flex-wrap items-center gap-2">
              {/* 미리보기 모드 선택 */}
              <div className="flex rounded-lg border">
                <Button
                  variant={previewMode === "desktop" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setPreviewMode("desktop")}
                  className="rounded-r-none"
                >
                  <Monitor className="h-3 w-3" />
                </Button>
                <Button
                  variant={previewMode === "tablet" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setPreviewMode("tablet")}
                  className="rounded-none"
                >
                  <Tablet className="h-3 w-3" />
                </Button>
                <Button
                  variant={previewMode === "mobile" ? "default" : "ghost"}
                  size="sm"
                  onClick={() => setPreviewMode("mobile")}
                  className="rounded-l-none"
                >
                  <Smartphone className="h-3 w-3" />
                </Button>
              </div>

              <Button variant="outline" size="sm" onClick={resetFormData}>
                초기화
              </Button>
              <Button variant="outline" size="sm" onClick={logFormData}>
                데이터 확인
              </Button>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* 미리보기 컨텐츠 */}
      <Card>
        <CardContent className="p-0">
          <div className={`${getPreviewStyles(previewMode)} min-h-screen bg-muted`}>
            {layout.components.length > 0 ? (
              renderGridLayout()
            ) : (
              <div className="flex min-h-screen items-center justify-center text-muted-foreground">
                <div className="text-center">
                  <Eye className="mx-auto mb-4 h-16 w-16 text-muted-foreground/30" />
                  <p>미리보기할 컴포넌트가 없습니다</p>
                  <p className="text-sm">화면 설계기에서 컴포넌트를 추가해주세요</p>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
