"use client"

import { useState, useRef } 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 { Camera, ImageIcon, LinkIcon, Upload } from "lucide-react"
import { useToast } from "@/hooks/use-toast"

interface ImageSelectorProps {
  value: string
  onChange: (url: string) => void
  label?: string
}

export function ImageSelector({ value, onChange, label = "Imagem" }: ImageSelectorProps) {
  const [urlInput, setUrlInput] = useState(value)
  const [isCapturing, setIsCapturing] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const cameraInputRef = useRef<HTMLInputElement>(null)
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const { toast } = useToast()

  const handleUrlSubmit = () => {
    if (urlInput.trim()) {
      onChange(urlInput.trim())
      toast({
        title: "URL adicionada",
        description: "A URL da imagem foi definida.",
      })
    }
  }

  const handleFileSelect = (file: File) => {
    if (!file.type.startsWith("image/")) {
      toast({
        title: "Arquivo inválido",
        description: "Por favor, selecione uma imagem válida.",
        variant: "destructive",
      })
      return
    }

    // Convert file to base64
    const reader = new FileReader()
    reader.onloadend = () => {
      const base64String = reader.result as string
      onChange(base64String)
      toast({
        title: "Imagem carregada",
        description: "A imagem foi carregada com sucesso.",
      })
    }
    reader.readAsDataURL(file)
  }

  const startCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true })
      if (videoRef.current) {
        videoRef.current.srcObject = stream
        videoRef.current.play()
        setIsCapturing(true)
      }
    } catch (error) {
      toast({
        title: "Erro ao acessar câmera",
        description: "Não foi possível acessar a câmera do dispositivo.",
        variant: "destructive",
      })
    }
  }

  const stopCamera = () => {
    if (videoRef.current?.srcObject) {
      const stream = videoRef.current.srcObject as MediaStream
      stream.getTracks().forEach((track) => track.stop())
      videoRef.current.srcObject = null
      setIsCapturing(false)
    }
  }

  const capturePhoto = () => {
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current
      const canvas = canvasRef.current
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      const ctx = canvas.getContext("2d")
      if (ctx) {
        ctx.drawImage(video, 0, 0)
        const imageDataUrl = canvas.toDataURL("image/jpeg", 0.9)
        onChange(imageDataUrl)
        stopCamera()
        toast({
          title: "Foto capturada",
          description: "A foto foi capturada com sucesso.",
        })
      }
    }
  }

  return (
    <div className="space-y-2">
      <Label>{label}</Label>
      <Tabs defaultValue="url" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="url">
            <LinkIcon className="h-4 w-4 mr-2" />
            URL
          </TabsTrigger>
          <TabsTrigger value="gallery">
            <ImageIcon className="h-4 w-4 mr-2" />
            Galeria
          </TabsTrigger>
          <TabsTrigger value="camera">
            <Camera className="h-4 w-4 mr-2" />
            Câmera
          </TabsTrigger>
        </TabsList>

        <TabsContent value="url" className="space-y-3">
          <Input
            type="url"
            placeholder="https://exemplo.com/imagem.jpg"
            value={urlInput}
            onChange={(e) => setUrlInput(e.target.value)}
          />
          <Button type="button" onClick={handleUrlSubmit} className="w-full">
            Usar URL
          </Button>
        </TabsContent>

        <TabsContent value="gallery" className="space-y-3">
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0]
              if (file) handleFileSelect(file)
            }}
          />
          <Button type="button" onClick={() => fileInputRef.current?.click()} className="w-full" variant="outline">
            <Upload className="h-4 w-4 mr-2" />
            Escolher da Galeria
          </Button>
          {value && value.startsWith("data:") && (
            <p className="text-xs text-muted-foreground text-center">Imagem carregada ✓</p>
          )}
        </TabsContent>

        <TabsContent value="camera" className="space-y-3">
          {!isCapturing ? (
            <Button type="button" onClick={startCamera} className="w-full bg-transparent" variant="outline">
              <Camera className="h-4 w-4 mr-2" />
              Iniciar Câmera
            </Button>
          ) : (
            <>
              <div className="relative aspect-video bg-black rounded-lg overflow-hidden">
                <video ref={videoRef} className="w-full h-full object-cover" />
              </div>
              <div className="flex gap-2">
                <Button type="button" onClick={capturePhoto} className="flex-1">
                  Capturar Foto
                </Button>
                <Button type="button" onClick={stopCamera} variant="outline" className="flex-1 bg-transparent">
                  Cancelar
                </Button>
              </div>
            </>
          )}
          <canvas ref={canvasRef} className="hidden" />
        </TabsContent>
      </Tabs>

      {value && !value.startsWith("data:") && (
        <div className="mt-2">
          <p className="text-xs text-muted-foreground break-all">URL atual: {value}</p>
        </div>
      )}
    </div>
  )
}
