import React, { useEffect, useRef, useState } from 'react'
import PSD from 'psd'

function PSDViewer({ file }) {
  const [imageSrc, setImageSrc] = useState('')
  const [text, setText] = useState('Your Text Here')
  const canvasRef = useRef(null)

  useEffect(() => {
    const loadPSD = async () => {
      try {
        const psd = await PSD.fromURL(file)
        const image = psd.image.toBase64() // Generate Base64 image
        setImageSrc(`data:image/png;base64,${image}`)
      } catch (error) {
        console.error('Error loading PSD file:', error)
      }
    }

    loadPSD()
  }, [file])

  useEffect(() => {
    if (imageSrc && canvasRef.current) {
      const canvas = canvasRef.current
      const ctx = canvas.getContext('2d')

      // Load the PSD image into the canvas
      const img = new Image()
      img.src = imageSrc
      img.onload = () => {
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0)

        // Add text overlay
        ctx.font = '48px Arial'
        ctx.fillStyle = 'red' // Customize text color
        ctx.fillText(text, 50, 100) // Customize position
      }
    }
  }, [imageSrc, text])

  const handleDownload = () => {
    const canvas = canvasRef.current
    const link = document.createElement('a')
    link.download = 'edited-psd.png'
    link.href = canvas.toDataURL('image/png')
    link.click()
  }

  return (
    <div>
      <h1>PSD Viewer and Editor</h1>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text to overlay"
      />
      <div>{imageSrc ? <canvas ref={canvasRef}></canvas> : <p>Loading PSD file...</p>}</div>
      <button onClick={handleDownload}>Download Edited Image</button>
    </div>
  )
}

function App() {
  return (
    <div>
      <PSDViewer file="/path/to/your-file.psd" />
    </div>
  )
}

export default App
