"use client"

import type React from "react"

import { useState, useRef } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Slider } from "@/components/ui/slider"
import { Badge } from "@/components/ui/badge"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Heart,
  Moon,
  Zap,
  Stethoscope,
  Pill,
  Dumbbell,
  Briefcase,
  Users,
  Sun,
  MapPin,
  Calendar,
  Tag,
  Camera,
  Mic,
  Save,
  ArrowLeft,
  Star,
} from "lucide-react"

interface MoodRegistrationProps {
  onBack: () => void
  onSave: (data: any) => void
}

export function MoodRegistration({ onBack, onSave }: MoodRegistrationProps) {
  const [registrationType, setRegistrationType] = useState<"quick" | "complete">("complete")

  // Mood data
  const [moodLevel, setMoodLevel] = useState([7])
  const [emotions, setEmotions] = useState<string[]>([])
  const [moodNotes, setMoodNotes] = useState("")

  // Physical factors
  const [sleepQuality, setSleepQuality] = useState(3)
  const [sleepHours, setSleepHours] = useState("")
  const [energyLevel, setEnergyLevel] = useState("medium")
  const [symptoms, setSymptoms] = useState<string[]>([])
  const [medications, setMedications] = useState<string[]>([])

  // Activities
  const [exerciseType, setExerciseType] = useState("")
  const [exerciseDuration, setExerciseDuration] = useState("")
  const [workHours, setWorkHours] = useState("")
  const [workStress, setWorkStress] = useState([5])
  const [socialTime, setSocialTime] = useState("friends")
  const [outdoorTime, setOutdoorTime] = useState("")

  // Context
  const [location, setLocation] = useState("")
  const [specialEvents, setSpecialEvents] = useState("")
  const [customTags, setCustomTags] = useState<string[]>([])
  const [newTag, setNewTag] = useState("")

  // Media
  const [photos, setPhotos] = useState<string[]>([])
  const [audioRecording, setAudioRecording] = useState<string | null>(null)
  const [isRecording, setIsRecording] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const mediaRecorderRef = useRef<MediaRecorder | null>(null)
  const audioChunksRef = useRef<Blob[]>([])

  const moodEmojis = ["😢", "😟", "😐", "🙂", "😊", "😄", "🤩", "🥳", "😍", "🌟"]

  const emotionOptions = [
    "Alegria",
    "Ansiedade",
    "Raiva",
    "Tristeza",
    "Calma",
    "Estresse",
    "Motivação",
    "Frustração",
    "Gratidão",
    "Preocupação",
  ]

  const symptomOptions = [
    "Dor de cabeça",
    "Tensão muscular",
    "Fadiga",
    "Insônia",
    "Náusea",
    "Tontura",
    "Dor nas costas",
    "Palpitações",
  ]

  const medicationOptions = [
    "Antidepressivo",
    "Ansiolítico",
    "Vitaminas",
    "Suplementos",
    "Analgésicos",
    "Outros medicamentos",
  ]

  const exerciseOptions = [
    "Caminhada",
    "Corrida",
    "Academia",
    "Yoga",
    "Natação",
    "Ciclismo",
    "Dança",
    "Esportes",
    "Alongamento",
  ]

  const toggleArrayItem = (array: string[], setArray: (arr: string[]) => void, item: string) => {
    setArray(array.includes(item) ? array.filter((i) => i !== item) : [...array, item])
  }

  const addCustomTag = () => {
    if (newTag.trim() && !customTags.includes(newTag.trim())) {
      setCustomTags([...customTags, newTag.trim()])
      setNewTag("")
    }
  }

  const handlePhotoCapture = () => {
    fileInputRef.current?.click()
  }

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file && file.type.startsWith("image/")) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const result = e.target?.result as string
        setPhotos((prev) => [...prev, result])
      }
      reader.readAsDataURL(file)
    }
  }

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      const mediaRecorder = new MediaRecorder(stream)
      mediaRecorderRef.current = mediaRecorder
      audioChunksRef.current = []

      mediaRecorder.ondataavailable = (event) => {
        audioChunksRef.current.push(event.data)
      }

      mediaRecorder.onstop = () => {
        const audioBlob = new Blob(audioChunksRef.current, { type: "audio/wav" })
        const audioUrl = URL.createObjectURL(audioBlob)
        setAudioRecording(audioUrl)
        stream.getTracks().forEach((track) => track.stop())
      }

      mediaRecorder.start()
      setIsRecording(true)
    } catch (error) {
      console.error("Erro ao acessar microfone:", error)
      alert("Não foi possível acessar o microfone. Verifique as permissões.")
    }
  }

  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop()
      setIsRecording(false)
    }
  }

  const handleVoiceNote = () => {
    if (isRecording) {
      stopRecording()
    } else {
      startRecording()
    }
  }

  const removePhoto = (index: number) => {
    setPhotos((prev) => prev.filter((_, i) => i !== index))
  }

  const removeAudio = () => {
    if (audioRecording) {
      URL.revokeObjectURL(audioRecording)
      setAudioRecording(null)
    }
  }

  const handleSave = () => {
    const data = {
      type: registrationType,
      mood: {
        level: moodLevel[0],
        emotions,
        notes: moodNotes,
      },
      physical: {
        sleepQuality,
        sleepHours: Number.parseFloat(sleepHours) || 0,
        energyLevel,
        symptoms,
        medications,
      },
      activities: {
        exercise: { type: exerciseType, duration: exerciseDuration },
        work: { hours: Number.parseFloat(workHours) || 0, stress: workStress[0] },
        socialTime,
        outdoorTime,
      },
      context: {
        location,
        specialEvents,
        customTags,
      },
      media: {
        photos,
        audioRecording,
      },
      timestamp: new Date().toISOString(),
    }

    onSave(data)
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <div className="bg-gradient-wellness p-4 text-white">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="sm" onClick={onBack} className="text-white hover:bg-white/20">
            <ArrowLeft className="w-4 h-4 border-black border-slate-50 border-black border-black" />
          </Button>
          <div>
            <h1 className="font-heading text-xl font-bold text-black text-black text-black">Registro de Humor</h1>
            <p className="text-sm text-black0 text-black text-slate-600">
              {new Date().toLocaleDateString("pt-BR", {
                weekday: "long",
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </p>
          </div>
        </div>
      </div>

      {/* Registration Type Toggle */}
      <div className="p-4">
        <Tabs value={registrationType} onValueChange={(value) => setRegistrationType(value as "quick" | "complete")}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="quick">Registro Rápido</TabsTrigger>
            <TabsTrigger value="complete">Registro Completo</TabsTrigger>
          </TabsList>

          <TabsContent value="quick" className="space-y-6 mt-6">
            {/* Quick Registration */}
            <Card className="neomorphic">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Heart className="w-5 h-5 text-primary" />
                  <span>Como você está?</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Humor (1-10)</span>
                    <div className="flex items-center space-x-2">
                      <span className="text-3xl">{moodEmojis[moodLevel[0] - 1]}</span>
                      <span className="font-bold text-xl">{moodLevel[0]}</span>
                    </div>
                  </div>
                  <Slider value={moodLevel} onValueChange={setMoodLevel} max={10} min={1} step={1} className="w-full" />
                </div>

                <div className="space-y-3">
                  <Label>Emoções principais</Label>
                  <div className="flex flex-wrap gap-2">
                    {emotionOptions.slice(0, 6).map((emotion) => (
                      <Badge
                        key={emotion}
                        variant={emotions.includes(emotion) ? "default" : "secondary"}
                        className="cursor-pointer"
                        onClick={() => toggleArrayItem(emotions, setEmotions, emotion)}
                      >
                        {emotion}
                      </Badge>
                    ))}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="quick-notes">Nota rápida (opcional)</Label>
                  <Textarea
                    id="quick-notes"
                    placeholder="Como foi seu dia?"
                    value={moodNotes}
                    onChange={(e) => setMoodNotes(e.target.value)}
                    rows={3}
                  />
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="complete" className="space-y-6 mt-6">
            {/* Complete Registration */}

            {/* Section 1: Base Mood */}
            <Card className="neomorphic">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Heart className="w-5 h-5 text-primary" />
                  <span>Humor Base</span>
                </CardTitle>
                <CardDescription>Como você está se sentindo agora?</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Nível do humor (1-10)</span>
                    <div className="flex items-center space-x-2">
                      <span className="text-3xl">{moodEmojis[moodLevel[0] - 1]}</span>
                      <span className="font-bold text-xl">{moodLevel[0]}</span>
                    </div>
                  </div>
                  <Slider value={moodLevel} onValueChange={setMoodLevel} max={10} min={1} step={1} className="w-full" />
                </div>

                <div className="space-y-3">
                  <Label>Emoções específicas</Label>
                  <div className="flex flex-wrap gap-2">
                    {emotionOptions.map((emotion) => (
                      <Badge
                        key={emotion}
                        variant={emotions.includes(emotion) ? "default" : "secondary"}
                        className="cursor-pointer"
                        onClick={() => toggleArrayItem(emotions, setEmotions, emotion)}
                      >
                        {emotion}
                      </Badge>
                    ))}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="mood-notes">Notas adicionais</Label>
                  <Textarea
                    id="mood-notes"
                    placeholder="Descreva como você está se sentindo..."
                    value={moodNotes}
                    onChange={(e) => setMoodNotes(e.target.value)}
                    rows={3}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Section 2: Physical Factors */}
            <Card className="neomorphic">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Stethoscope className="w-5 h-5 text-primary" />
                  <span>Fatores Físicos</span>
                </CardTitle>
                <CardDescription>Como está seu corpo hoje?</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="flex items-center space-x-2">
                      <Moon className="w-4 h-4" />
                      <span>Qualidade do sono</span>
                    </Label>
                    <div className="flex space-x-1">
                      {[1, 2, 3, 4, 5].map((star) => (
                        <Star
                          key={star}
                          className={`w-6 h-6 cursor-pointer ${
                            star <= sleepQuality ? "text-yellow-500 fill-current" : "text-gray-300"
                          }`}
                          onClick={() => setSleepQuality(star)}
                        />
                      ))}
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="sleep-hours">Horas de sono</Label>
                    <Input
                      id="sleep-hours"
                      type="number"
                      placeholder="8"
                      value={sleepHours}
                      onChange={(e) => setSleepHours(e.target.value)}
                      min="0"
                      max="24"
                      step="0.5"
                    />
                  </div>
                </div>

                <div className="space-y-3">
                  <Label className="flex items-center space-x-2">
                    <Zap className="w-4 h-4" />
                    <span>Nível de energia</span>
                  </Label>
                  <RadioGroup value={energyLevel} onValueChange={setEnergyLevel}>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="low" id="energy-low" />
                      <Label htmlFor="energy-low">Baixo</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="medium" id="energy-medium" />
                      <Label htmlFor="energy-medium">Médio</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="high" id="energy-high" />
                      <Label htmlFor="energy-high">Alto</Label>
                    </div>
                  </RadioGroup>
                </div>

                <div className="space-y-3">
                  <Label>Sintomas físicos</Label>
                  <div className="flex flex-wrap gap-2">
                    {symptomOptions.map((symptom) => (
                      <Badge
                        key={symptom}
                        variant={symptoms.includes(symptom) ? "default" : "secondary"}
                        className="cursor-pointer"
                        onClick={() => toggleArrayItem(symptoms, setSymptoms, symptom)}
                      >
                        {symptom}
                      </Badge>
                    ))}
                  </div>
                </div>

                <div className="space-y-3">
                  <Label className="flex items-center space-x-2">
                    <Pill className="w-4 h-4" />
                    <span>Medicamentos tomados</span>
                  </Label>
                  <div className="flex flex-wrap gap-2">
                    {medicationOptions.map((medication) => (
                      <Badge
                        key={medication}
                        variant={medications.includes(medication) ? "default" : "secondary"}
                        className="cursor-pointer"
                        onClick={() => toggleArrayItem(medications, setMedications, medication)}
                      >
                        {medication}
                      </Badge>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Section 3: Activities */}
            <Card className="neomorphic">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Dumbbell className="w-5 h-5 text-primary" />
                  <span>Atividades</span>
                </CardTitle>
                <CardDescription>O que você fez hoje?</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Tipo de exercício</Label>
                    <div className="flex flex-wrap gap-1">
                      {exerciseOptions.slice(0, 4).map((exercise) => (
                        <Badge
                          key={exercise}
                          variant={exerciseType === exercise ? "default" : "secondary"}
                          className="cursor-pointer text-xs"
                          onClick={() => setExerciseType(exercise)}
                        >
                          {exercise}
                        </Badge>
                      ))}
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="exercise-duration">Duração (min)</Label>
                    <Input
                      id="exercise-duration"
                      type="number"
                      placeholder="30"
                      value={exerciseDuration}
                      onChange={(e) => setExerciseDuration(e.target.value)}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="work-hours" className="flex items-center space-x-2">
                      <Briefcase className="w-4 h-4" />
                      <span>Horas trabalho/estudo</span>
                    </Label>
                    <Input
                      id="work-hours"
                      type="number"
                      placeholder="8"
                      value={workHours}
                      onChange={(e) => setWorkHours(e.target.value)}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>Nível de estresse no trabalho</Label>
                    <Slider
                      value={workStress}
                      onValueChange={setWorkStress}
                      max={10}
                      min={1}
                      step={1}
                      className="w-full"
                    />
                    <div className="text-center text-sm text-muted-foreground">{workStress[0]}/10</div>
                  </div>
                </div>

                <div className="space-y-3">
                  <Label className="flex items-center space-x-2">
                    <Users className="w-4 h-4" />
                    <span>Tempo social</span>
                  </Label>
                  <RadioGroup value={socialTime} onValueChange={setSocialTime}>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="alone" id="social-alone" />
                      <Label htmlFor="social-alone">Sozinho</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="friends" id="social-friends" />
                      <Label htmlFor="social-friends">Com amigos</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="family" id="social-family" />
                      <Label htmlFor="social-family">Com família</Label>
                    </div>
                  </RadioGroup>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="outdoor-time" className="flex items-center space-x-2">
                    <Sun className="w-4 h-4" />
                    <span>Tempo ao ar livre (min)</span>
                  </Label>
                  <Input
                    id="outdoor-time"
                    type="number"
                    placeholder="60"
                    value={outdoorTime}
                    onChange={(e) => setOutdoorTime(e.target.value)}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Section 4: Context */}
            <Card className="neomorphic">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <MapPin className="w-5 h-5 text-primary" />
                  <span>Contexto</span>
                </CardTitle>
                <CardDescription>Onde e o que aconteceu?</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="location">Localização (opcional)</Label>
                  <Input
                    id="location"
                    placeholder="Casa, trabalho, parque..."
                    value={location}
                    onChange={(e) => setLocation(e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="special-events" className="flex items-center space-x-2">
                    <Calendar className="w-4 h-4" />
                    <span>Eventos especiais</span>
                  </Label>
                  <Input
                    id="special-events"
                    placeholder="Reunião importante, encontro com amigos..."
                    value={specialEvents}
                    onChange={(e) => setSpecialEvents(e.target.value)}
                  />
                </div>

                <div className="space-y-3">
                  <Label className="flex items-center space-x-2">
                    <Tag className="w-4 h-4" />
                    <span>Tags personalizadas</span>
                  </Label>
                  <div className="flex space-x-2">
                    <Input
                      placeholder="Adicionar tag..."
                      value={newTag}
                      onChange={(e) => setNewTag(e.target.value)}
                      onKeyPress={(e) => e.key === "Enter" && addCustomTag()}
                    />
                    <Button onClick={addCustomTag} size="sm">
                      Adicionar
                    </Button>
                  </div>
                  {customTags.length > 0 && (
                    <div className="flex flex-wrap gap-2">
                      {customTags.map((tag) => (
                        <Badge
                          key={tag}
                          variant="outline"
                          className="cursor-pointer"
                          onClick={() => setCustomTags(customTags.filter((t) => t !== tag))}
                        >
                          {tag} ×
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>

                <div className="flex space-x-2">
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleFileSelect}
                    className="hidden"
                  />
                  <Button
                    variant="outline"
                    size="sm"
                    className="flex items-center space-x-2 bg-transparent"
                    onClick={handlePhotoCapture}
                    type="button"
                  >
                    <Camera className="w-4 h-4" />
                    <span>Adicionar foto</span>
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className={`flex items-center space-x-2 ${isRecording ? "bg-red-100 text-red-600" : "bg-transparent"}`}
                    onClick={handleVoiceNote}
                    type="button"
                  >
                    <Mic className="w-4 h-4" />
                    <span>{isRecording ? "Parar gravação" : "Nota de voz"}</span>
                  </Button>
                </div>

                {photos.length > 0 && (
                  <div className="space-y-2">
                    <Label>Fotos adicionadas</Label>
                    <div className="flex flex-wrap gap-2">
                      {photos.map((photo, index) => (
                        <div key={index} className="relative">
                          <img
                            src={photo || "/placeholder.svg"}
                            alt={`Foto ${index + 1}`}
                            className="w-20 h-20 object-cover rounded border"
                          />
                          <Button
                            variant="destructive"
                            size="sm"
                            className="absolute -top-2 -right-2 w-6 h-6 rounded-full p-0"
                            onClick={() => removePhoto(index)}
                          >
                            ×
                          </Button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {audioRecording && (
                  <div className="space-y-2">
                    <Label>Nota de voz</Label>
                    <div className="flex items-center space-x-2 p-2 border rounded">
                      <audio controls src={audioRecording} className="flex-1" />
                      <Button variant="destructive" size="sm" onClick={removeAudio}>
                        Remover
                      </Button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Save Button */}
        <div className="sticky bottom-0 bg-background p-4 border-t border-border mt-6">
          <Button onClick={handleSave} className="w-full" size="lg">
            <Save className="w-4 h-4 mr-2" />
            Salvar Registro
          </Button>
        </div>
      </div>
    </div>
  )
}