"use client"

import type React from "react"

import { useEffect, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Slider } from "@/components/ui/slider"
import { Bold, Download, ImageIcon, List, Palette, Type } from "lucide-react"
import ColorPicker from "@/components/color-picker"

type Layer = {
  id: string
  type: "text" | "image" | "bullet"
  content: string
  x: number
  y: number
  isBold: boolean
  color: string
  fontSize: number
  selected: boolean
  width?: number
  height?: number
}

export default function Editor() {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [layers, setLayers] = useState<Layer[]>([])
  const [selectedLayerId, setSelectedLayerId] = useState<string | null>(null)
  const [textInput, setTextInput] = useState("")
  const [isBold, setIsBold] = useState(false)
  const [color, setColor] = useState("#000000")
  const [fontSize, setFontSize] = useState(24)
  const [backgroundLoaded, setBackgroundLoaded] = useState(false)
  const [isDragging, setIsDragging] = useState(false)
  const [dragStartPos, setDragStartPos] = useState({ x: 0, y: 0 })
  const [isResizing, setIsResizing] = useState(false)
  const [resizeStartSize, setResizeStartSize] = useState({ width: 0, height: 0 })
  const [backgroundImage, setBackgroundImage] = useState<HTMLImageElement | null>(null)
  const [showInstructions, setShowInstructions] = useState(true)
  const scale = 0.4 // 40% of original size

  // Load background image once
  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext("2d")
    if (!ctx) return

    const img = new Image()
    img.crossOrigin = "anonymous"
    img.src = "/abstract-geometric-background.png"
    img.onload = () => {
      // Store the background image for reuse
      setBackgroundImage(img)
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      setBackgroundLoaded(true)
    }
  }, [])

  // Redraw canvas when layers change
  useEffect(() => {
    if (!backgroundLoaded || !backgroundImage) return

    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext("2d")
    if (!ctx) return

    // Clear canvas and redraw background
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height)

    // Draw all layers
    layers.forEach((layer) => {
      if (layer.type === "text" || layer.type === "bullet") {
        ctx.font = `${layer.isBold ? "bold" : "normal"} ${layer.fontSize}px Arial`
        ctx.fillStyle = layer.color

        if (layer.type === "bullet") {
          // Draw bullet point
          ctx.fillText("• " + layer.content, layer.x, layer.y)
        } else {
          ctx.fillText(layer.content, layer.x, layer.y)
        }

        // Draw selection box if selected
        if (layer.selected) {
          const metrics = ctx.measureText(layer.type === "bullet" ? "• " + layer.content : layer.content)
          const height = layer.fontSize * 1.2
          ctx.strokeStyle = "#0070f3"
          ctx.lineWidth = 2
          ctx.strokeRect(layer.x - 5, layer.y - height + 5, metrics.width + 10, height + 10)

          // Draw resize handle
          ctx.fillStyle = "#0070f3"
          ctx.fillRect(layer.x + metrics.width + 5, layer.y - 5, 10, 10)
        }
      } else if (layer.type === "image" && layer.width && layer.height) {
        const img = new Image()
        img.crossOrigin = "anonymous"
        img.src = layer.content
        img.onload = () => {
          ctx.drawImage(img, layer.x, layer.y, layer.width, layer.height)

          // Draw selection box if selected
          if (layer.selected) {
            ctx.strokeStyle = "#0070f3"
            ctx.lineWidth = 2
            ctx.strokeRect(layer.x - 5, layer.y - 5, layer.width + 10, layer.height + 10)

            // Draw resize handle
            ctx.fillStyle = "#0070f3"
            ctx.fillRect(layer.x + layer.width + 5, layer.y + layer.height + 5, 10, 10)
          }
        }
      }
    })
  }, [layers, backgroundLoaded, backgroundImage])

  const addTextLayer = (type: "text" | "bullet") => {
    if (!textInput.trim()) {
      console.log("Text input is empty")
      return
    }

    const newLayer: Layer = {
      id: Date.now().toString(),
      type,
      content: textInput,
      x: 100,
      y: 100 + layers.length * 50,
      isBold,
      color,
      fontSize,
      selected: true,
    }

    console.log("Adding new layer:", newLayer)
    setLayers(layers.map((layer) => ({ ...layer, selected: false })).concat(newLayer))
    setSelectedLayerId(newLayer.id)
    setTextInput("")
  }

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = (event) => {
      const img = new Image()
      img.crossOrigin = "anonymous"
      img.src = event.target?.result as string
      img.onload = () => {
        // Scale image to fit within canvas while maintaining aspect ratio
        let width = img.width
        let height = img.height
        const maxDimension = 500

        if (width > maxDimension || height > maxDimension) {
          if (width > height) {
            height = (height / width) * maxDimension
            width = maxDimension
          } else {
            width = (width / height) * maxDimension
            height = maxDimension
          }
        }

        const newLayer: Layer = {
          id: Date.now().toString(),
          type: "image",
          content: event.target?.result as string,
          x: 100,
          y: 100,
          isBold: false,
          color: "#000000",
          fontSize: 24,
          selected: true,
          width,
          height,
        }

        setLayers(layers.map((layer) => ({ ...layer, selected: false })).concat(newLayer))
        setSelectedLayerId(newLayer.id)
      }
    }
    reader.readAsDataURL(file)
  }

  const updateSelectedLayer = () => {
    if (!selectedLayerId) return

    setLayers(
      layers.map((layer) => {
        if (layer.id === selectedLayerId) {
          return {
            ...layer,
            isBold,
            color,
            fontSize,
          }
        }
        return layer
      }),
    )
  }

  const handleCanvasClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = canvasRef.current
    if (!canvas) return

    const rect = canvas.getBoundingClientRect()
    const x = (e.clientX - rect.left) * (canvas.width / rect.width)
    const y = (e.clientY - rect.top) * (canvas.height / rect.height)

    // Check if clicked on any layer
    let clickedLayer = false
    const updatedLayers = layers.map((layer) => {
      let isClicked = false

      if (layer.type === "text" || layer.type === "bullet") {
        const ctx = canvas.getContext("2d")
        if (ctx) {
          ctx.font = `${layer.isBold ? "bold" : "normal"} ${layer.fontSize}px Arial`
          const metrics = ctx.measureText(layer.type === "bullet" ? "• " + layer.content : layer.content)
          const height = layer.fontSize * 1.2

          isClicked =
            x >= layer.x - 5 && x <= layer.x + metrics.width + 5 && y >= layer.y - height + 5 && y <= layer.y + 5
        }
      } else if (layer.type === "image" && layer.width && layer.height) {
        isClicked = x >= layer.x && x <= layer.x + layer.width && y >= layer.y && y <= layer.y + layer.height
      }

      if (isClicked) {
        clickedLayer = true
        setSelectedLayerId(layer.id)

        // Update UI controls to match the selected layer's properties
        if (layer.type === "text" || layer.type === "bullet") {
          setIsBold(layer.isBold)
          setColor(layer.color)
          setFontSize(layer.fontSize)
        }

        return { ...layer, selected: true }
      }
      return { ...layer, selected: false }
    })

    if (clickedLayer) {
      setLayers(updatedLayers)
    } else {
      // Deselect all if clicked on empty space
      setLayers(layers.map((layer) => ({ ...layer, selected: false })))
      setSelectedLayerId(null)
    }
  }

  const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!selectedLayerId) return

    const canvas = canvasRef.current
    if (!canvas) return

    const rect = canvas.getBoundingClientRect()
    const x = (e.clientX - rect.left) * (canvas.width / rect.width)
    const y = (e.clientY - rect.top) * (canvas.height / rect.height)

    const selectedLayer = layers.find((layer) => layer.id === selectedLayerId)
    if (!selectedLayer) return

    // Check if clicking on resize handle
    if (selectedLayer.type === "text" || selectedLayer.type === "bullet") {
      const ctx = canvas.getContext("2d")
      if (ctx) {
        ctx.font = `${selectedLayer.isBold ? "bold" : "normal"} ${selectedLayer.fontSize}px Arial`
        const metrics = ctx.measureText(
          selectedLayer.type === "bullet" ? "• " + selectedLayer.content : selectedLayer.content,
        )

        // Check if clicking on resize handle (bottom right corner)
        if (
          x >= selectedLayer.x + metrics.width + 5 &&
          x <= selectedLayer.x + metrics.width + 15 &&
          y >= selectedLayer.y - 5 &&
          y <= selectedLayer.y + 5
        ) {
          setIsResizing(true)
          setResizeStartSize({ width: metrics.width, height: selectedLayer.fontSize })
          return
        }
      }
    } else if (selectedLayer.type === "image" && selectedLayer.width && selectedLayer.height) {
      // Check if clicking on resize handle (bottom right corner)
      if (
        x >= selectedLayer.x + selectedLayer.width + 5 &&
        x <= selectedLayer.x + selectedLayer.width + 15 &&
        y >= selectedLayer.y + selectedLayer.height + 5 &&
        y <= selectedLayer.y + selectedLayer.height + 15
      ) {
        setIsResizing(true)
        setResizeStartSize({ width: selectedLayer.width, height: selectedLayer.height })
        return
      }
    }

    // If not resizing, then dragging
    setIsDragging(true)
    setDragStartPos({ x: x - selectedLayer.x, y: y - selectedLayer.y })
  }

  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!selectedLayerId) return

    const canvas = canvasRef.current
    if (!canvas) return

    const rect = canvas.getBoundingClientRect()
    const x = (e.clientX - rect.left) * (canvas.width / rect.width)
    const y = (e.clientY - rect.top) * (canvas.height / rect.height)

    if (isResizing) {
      const selectedLayer = layers.find((layer) => layer.id === selectedLayerId)
      if (!selectedLayer) return

      if (selectedLayer.type === "text" || selectedLayer.type === "bullet") {
        // For text, we resize by changing font size
        const scaleFactor = (x - selectedLayer.x) / resizeStartSize.width
        const newFontSize = Math.max(12, Math.min(72, Math.round(resizeStartSize.height * scaleFactor)))

        setLayers(
          layers.map((layer) => {
            if (layer.id === selectedLayerId) {
              return {
                ...layer,
                fontSize: newFontSize,
              }
            }
            return layer
          }),
        )

        // Update the fontSize state to reflect in the UI
        setFontSize(newFontSize)
      } else if (selectedLayer.type === "image") {
        // For images, we resize width and height
        const newWidth = Math.max(20, x - selectedLayer.x)
        const aspectRatio = resizeStartSize.height / resizeStartSize.width
        const newHeight = newWidth * aspectRatio

        setLayers(
          layers.map((layer) => {
            if (layer.id === selectedLayerId) {
              return {
                ...layer,
                width: newWidth,
                height: newHeight,
              }
            }
            return layer
          }),
        )
      }
    } else if (isDragging) {
      setLayers(
        layers.map((layer) => {
          if (layer.id === selectedLayerId) {
            return {
              ...layer,
              x: x - dragStartPos.x,
              y: y - dragStartPos.y,
            }
          }
          return layer
        }),
      )
    }
  }

  const handleMouseUp = () => {
    setIsDragging(false)
    setIsResizing(false)
  }

  const exportImage = () => {
    const canvas = canvasRef.current
    if (!canvas) return

    // Create a temporary link element
    const link = document.createElement("a")
    link.download = "image-editor-export.png"
    link.href = canvas.toDataURL("image/png")
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  const deleteSelectedLayer = () => {
    if (!selectedLayerId) return
    setLayers(layers.filter((layer) => layer.id !== selectedLayerId))
    setSelectedLayerId(null)
  }

  console.log("Current layers:", layers)
  console.log("Text input:", textInput)

  return (
    <div className="flex flex-col min-h-screen">
      <header className="border-b p-4 bg-white flex justify-between items-center">
        <h1 className="text-2xl font-bold">Image Editor</h1>
        <Button variant="outline" onClick={() => setShowInstructions(true)}>
          How to Use
        </Button>
      </header>

      <div className="flex flex-1 overflow-hidden">
        {/* Canvas Area */}
        <div className="flex-1 p-4 bg-gray-100 flex flex-col">
          <div className="relative bg-white shadow-md rounded-md overflow-hidden max-w-3xl mx-auto flex-1 flex items-center justify-center">
            <div style={{ width: `${2000 * scale}px`, height: `${2000 * scale}px` }} className="relative">
              <canvas
                ref={canvasRef}
                width={2000}
                height={2000}
                style={{ width: "100%", height: "100%" }}
                onClick={handleCanvasClick}
                onMouseDown={handleMouseDown}
                onMouseMove={handleMouseMove}
                onMouseUp={handleMouseUp}
                onMouseLeave={handleMouseUp}
              />
            </div>
          </div>
        </div>

        {/* Tools Panel */}
        <div className="w-80 border-l bg-white p-4 overflow-y-auto">
          <Tabs defaultValue="text">
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="text">
                <Type className="h-4 w-4 mr-2" />
                Text
              </TabsTrigger>
              <TabsTrigger value="image">
                <ImageIcon className="h-4 w-4 mr-2" />
                Image
              </TabsTrigger>
              <TabsTrigger value="bullet">
                <List className="h-4 w-4 mr-2" />
                Bullet
              </TabsTrigger>
            </TabsList>

            <TabsContent value="text" className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="text-input">Text Content</Label>
                <Input
                  id="text-input"
                  value={textInput}
                  onChange={(e) => setTextInput(e.target.value)}
                  placeholder="Enter text"
                />
              </div>

              <div className="flex items-center space-x-2">
                <Button
                  variant={isBold ? "default" : "outline"}
                  size="icon"
                  onClick={() => {
                    const newBoldState = !isBold
                    setIsBold(newBoldState)
                    if (selectedLayerId) {
                      setLayers(
                        layers.map((layer) => {
                          if (layer.id === selectedLayerId && (layer.type === "text" || layer.type === "bullet")) {
                            return {
                              ...layer,
                              isBold: newBoldState,
                            }
                          }
                          return layer
                        }),
                      )
                    }
                  }}
                  type="button"
                >
                  <Bold className="h-4 w-4" />
                </Button>
                <div className="flex items-center space-x-2">
                  <Palette className="h-4 w-4" />
                  <ColorPicker
                    color={color}
                    onChange={(newColor) => {
                      setColor(newColor)
                      if (selectedLayerId) {
                        setLayers(
                          layers.map((layer) => {
                            if (layer.id === selectedLayerId && (layer.type === "text" || layer.type === "bullet")) {
                              return {
                                ...layer,
                                color: newColor,
                              }
                            }
                            return layer
                          }),
                        )
                      }
                    }}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label>Font Size: {fontSize}px</Label>
                <Slider
                  value={[fontSize]}
                  min={12}
                  max={72}
                  step={1}
                  onValueChange={(value) => {
                    setFontSize(value[0])
                    if (selectedLayerId) {
                      setLayers(
                        layers.map((layer) => {
                          if (layer.id === selectedLayerId && (layer.type === "text" || layer.type === "bullet")) {
                            return {
                              ...layer,
                              fontSize: value[0],
                            }
                          }
                          return layer
                        }),
                      )
                    }
                  }}
                />
              </div>

              <Button onClick={() => addTextLayer("text")} className="w-full">
                Add Text
              </Button>
            </TabsContent>

            <TabsContent value="image" className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="image-upload">Upload Image</Label>
                <Input id="image-upload" type="file" accept="image/*" onChange={handleImageUpload} />
              </div>
            </TabsContent>

            <TabsContent value="bullet" className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="bullet-input">Bullet Point Text</Label>
                <Input
                  id="bullet-input"
                  value={textInput}
                  onChange={(e) => setTextInput(e.target.value)}
                  placeholder="Enter bullet point text"
                />
              </div>

              <div className="flex items-center space-x-2">
                <Button
                  variant={isBold ? "default" : "outline"}
                  size="icon"
                  onClick={() => {
                    const newBoldState = !isBold
                    setIsBold(newBoldState)
                    if (selectedLayerId) {
                      setLayers(
                        layers.map((layer) => {
                          if (layer.id === selectedLayerId && (layer.type === "text" || layer.type === "bullet")) {
                            return {
                              ...layer,
                              isBold: newBoldState,
                            }
                          }
                          return layer
                        }),
                      )
                    }
                  }}
                  type="button"
                >
                  <Bold className="h-4 w-4" />
                </Button>
                <div className="flex items-center space-x-2">
                  <Palette className="h-4 w-4" />
                  <ColorPicker
                    color={color}
                    onChange={(newColor) => {
                      setColor(newColor)
                      if (selectedLayerId) {
                        setLayers(
                          layers.map((layer) => {
                            if (layer.id === selectedLayerId && (layer.type === "text" || layer.type === "bullet")) {
                              return {
                                ...layer,
                                color: newColor,
                              }
                            }
                            return layer
                          }),
                        )
                      }
                    }}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label>Font Size: {fontSize}px</Label>
                <Slider
                  value={[fontSize]}
                  min={12}
                  max={72}
                  step={1}
                  onValueChange={(value) => {
                    setFontSize(value[0])
                    if (selectedLayerId) {
                      setLayers(
                        layers.map((layer) => {
                          if (layer.id === selectedLayerId && (layer.type === "text" || layer.type === "bullet")) {
                            return {
                              ...layer,
                              fontSize: value[0],
                            }
                          }
                          return layer
                        }),
                      )
                    }
                  }}
                />
              </div>

              <Button onClick={() => addTextLayer("bullet")} className="w-full">
                Add Bullet Point
              </Button>
            </TabsContent>
          </Tabs>

          <div className="mt-8 space-y-4">
            <Button onClick={exportImage} className="w-full" variant="default">
              <Download className="h-4 w-4 mr-2" />
              Export as PNG
            </Button>

            {selectedLayerId && (
              <Button onClick={deleteSelectedLayer} className="w-full" variant="destructive">
                Delete Selected Layer
              </Button>
            )}
          </div>
        </div>
      </div>

      <footer className="border-t p-3 bg-white text-center text-sm text-gray-500">Developed by SimonTodd</footer>

      {showInstructions && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-lg shadow-lg max-w-2xl w-full max-h-[80vh] overflow-y-auto">
            <h2 className="text-2xl font-bold mb-4">How to Use the Image Editor</h2>

            <div className="space-y-4">
              <div>
                <h3 className="text-lg font-semibold">Adding Content</h3>
                <ul className="list-disc pl-5 space-y-2">
                  <li>
                    Select the <strong>Text</strong> tab to add regular text
                  </li>
                  <li>
                    Select the <strong>Bullet</strong> tab to add bullet points
                  </li>
                  <li>
                    Select the <strong>Image</strong> tab to upload and add images
                  </li>
                </ul>
              </div>

              <div>
                <h3 className="text-lg font-semibold">Editing Text</h3>
                <ul className="list-disc pl-5 space-y-2">
                  <li>Click on any text to select it</li>
                  <li>Use the Bold button, Color picker, and Font Size slider to modify the selected text</li>
                  <li>Changes are applied in real-time as you adjust the controls</li>
                </ul>
              </div>

              <div>
                <h3 className="text-lg font-semibold">Moving & Resizing</h3>
                <ul className="list-disc pl-5 space-y-2">
                  <li>Click and drag any element to move it around</li>
                  <li>To resize text: select it and drag the blue handle on the right side</li>
                  <li>To resize images: select it and drag the blue handle on the bottom-right corner</li>
                </ul>
              </div>

              <div>
                <h3 className="text-lg font-semibold">Exporting</h3>
                <ul className="list-disc pl-5 space-y-2">
                  <li>Click the "Export as PNG" button to download your creation</li>
                  <li>The exported image will be full resolution (2000x2000px)</li>
                </ul>
              </div>
            </div>

            <div className="mt-6 text-center text-sm text-gray-500">Developed by SimonTodd</div>

            <Button onClick={() => setShowInstructions(false)} className="mt-4 w-full">
              Got it!
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
