'use client'

import { useState, useCallback, useRef } from 'react'
import { Crosshair } from 'lucide-react'

interface FocalPointPickerProps {
  imageUrl: string
  focalX: number
  focalY: number
  onChange: (x: number, y: number) => void
}

export function FocalPointPicker({ imageUrl, focalX, focalY, onChange }: FocalPointPickerProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const [dragging, setDragging] = useState(false)

  const handlePosition = useCallback(
    (e: React.MouseEvent) => {
      const rect = containerRef.current?.getBoundingClientRect()
      if (!rect) return
      const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
      const y = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height))
      onChange(Math.round(x * 100) / 100, Math.round(y * 100) / 100)
    },
    [onChange],
  )

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">
        <Crosshair className="h-4 w-4" />
        Focal Point
      </div>
      <div
        ref={containerRef}
        className="relative cursor-crosshair overflow-hidden rounded-lg border border-[var(--border)] select-none"
        style={{ maxHeight: '200px' }}
        onClick={handlePosition}
        onMouseDown={() => setDragging(true)}
        onMouseUp={() => setDragging(false)}
        onMouseLeave={() => setDragging(false)}
        onMouseMove={(e) => {
          if (dragging) handlePosition(e)
        }}
      >
        <img
          src={imageUrl}
          alt="Focal point preview"
          className="h-full w-full object-contain"
          draggable={false}
        />
        <div
          className="bg-info/50 pointer-events-none absolute -mt-3 -ml-3 h-6 w-6 rounded-full border-2 border-white shadow-lg"
          style={{ left: `${focalX * 100}%`, top: `${focalY * 100}%` }}
        >
          <div className="bg-card absolute inset-1 rounded-full" />
        </div>
      </div>
      <p className="text-xs text-[var(--muted-foreground)]">
        Click or drag to set the focal point ({Math.round(focalX * 100)}%,{' '}
        {Math.round(focalY * 100)}%)
      </p>
    </div>
  )
}
