"use client"

import type React from "react"

import { useState, useRef } from "react"
import { useNavigate } from "react-router-dom"
import { recipeService } from "@/api/recipe"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Mic, Upload, ArrowLeft, Loader2 } from "lucide-react"
import { motion } from "framer-motion"
import { KitchenIllustration } from "@/components/illustrations/KitchenIllustration"
import { CookingLoader } from "@/components/illustrations/CookingLoader"

export default function RecipeForm() {
  const navigate = useNavigate()
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [audioFile, setAudioFile] = useState<File | null>(null)
  const [isRecording, setIsRecording] = useState(false)
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null)
  const [recordingStatus, setRecordingStatus] = useState<"idle" | "recording" | "processing">("idle")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  // Gérer l'upload de fichier audio
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setAudioFile(e.target.files[0])
      setError("")
    }
  }

  // Démarrer l'enregistrement audio
  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      const recorder = new MediaRecorder(stream)
      setMediaRecorder(recorder)

      const chunks: BlobPart[] = []
      recorder.ondataavailable = (e) => {
        chunks.push(e.data)
      }

      recorder.onstop = () => {
        const blob = new Blob(chunks, { type: "audio/webm" })
        const file = new File([blob], "recording.webm", { type: "audio/webm" })
        setAudioFile(file)
        setRecordingStatus("idle")
        setError("")
      }

      recorder.start()
      setIsRecording(true)
      setRecordingStatus("recording")
    } catch (err) {
      console.error("Erreur lors de l'accès au microphone:", err)
      setError("Impossible d'accéder au microphone. Vérifiez les permissions.")
    }
  }

  // Arrêter l'enregistrement audio
  const stopRecording = () => {
    if (mediaRecorder && isRecording) {
      mediaRecorder.stop()
      setIsRecording(false)
      setRecordingStatus("processing")

      // Arrêter toutes les pistes audio
      mediaRecorder.stream.getTracks().forEach((track) => track.stop())
    }
  }

  // Soumettre le formulaire
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!audioFile) {
      setError("Veuillez fournir un enregistrement audio des ingrédients")
      return
    }

    setLoading(true)
    setError("")
    setRecordingStatus("processing")

    try {
      const recipe = await recipeService.createRecipe(audioFile)
      navigate(`/recipes/${recipe.id}`)
    } catch (err) {
      console.error("Erreur lors de la création de la recette:", err)
      setError(err instanceof Error ? err.message : "Une erreur est survenue lors de la création de la recette")
      setRecordingStatus("idle")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="h-full flex flex-col bg-gradient-to-b from-amber-50 to-orange-50 dark:from-slate-950 dark:to-slate-900">
      <div className="p-2 sm:p-4">
        <Button
          variant="ghost"
          className="cursor-pointer flex items-center gap-2"
          onClick={() => navigate("/recipes")}
        >
          <ArrowLeft className="h-4 w-4" />
          Retour aux recettes
        </Button>
      </div>

      <div className="w-full space-y-4 sm:space-y-6 mt-2 sm:mt-4 px-2 sm:px-4 md:px-6 lg:px-8 max-w-3xl mx-auto">
        {/* Illustrations */}
        <div className="flex flex-col items-center text-center mb-4 sm:mb-8">
          <KitchenIllustration
            height={150}
          />
          <p className="max-w-[900px] text-muted-foreground text-sm md:text-xl/relaxed mt-2 sm:mt-4">
            Notre intelligence artificielle transforme votre façon de cuisiner
          </p>
        </div>

        <Card className="border-none shadow-lg">
          <CardHeader className="p-4 sm:p-6">
            <CardTitle className="text-xl sm:text-2xl">Créer une nouvelle recette</CardTitle>
            <CardDescription className="text-sm">
              Enregistrez ou téléchargez un fichier audio listant les ingrédients disponibles, et nous générerons une
              recette pour vous.
            </CardDescription>
          </CardHeader>

          <CardContent className="p-4 sm:p-6">
            {error && (
              <div className="rounded-md bg-red-50 p-4 text-sm text-red-700 dark:bg-red-900/50 dark:text-red-200 mb-4">
                {error}
              </div>
            )}

            {recordingStatus !== "processing" && !loading && (
              <div className="space-y-4">
                {audioFile && (
                  <div className="rounded-lg bg-green-50 dark:bg-green-900/20 p-4">
                    <p className="font-medium text-green-800 dark:text-green-300">Fichier audio prêt !</p>
                    <p className="text-sm text-green-700 dark:text-green-400 mt-1">
                      {audioFile.name} ({(audioFile.size / 1024).toFixed(2)} KB)
                    </p>

                    <div className="mt-3">
                      <audio controls className="w-full">
                        <source src={URL.createObjectURL(audioFile)} type={audioFile.type} />
                        Votre navigateur ne supporte pas la lecture audio.
                      </audio>
                    </div>
                  </div>
                )}

                <p className="text-sm text-muted-foreground">
                  Enregistrez-vous en listant les ingrédients que vous avez à disposition. Notre IA générera une
                  recette adaptée à ces ingrédients.
                </p>
              </div>
            )}

            {(recordingStatus === "processing" || loading) && (
              <div className="py-8 flex flex-col items-center justify-center">
                <CookingLoader />
                <p className="mt-4 text-center font-medium">Préparation de votre recette...</p>
                <p className="text-sm text-muted-foreground text-center mt-2">
                  Notre chef IA mijote quelque chose de délicieux avec vos ingrédients
                </p>
              </div>
            )}
          </CardContent>

          <CardFooter className="p-4 sm:p-6 flex justify-between">
            <Button
              variant="outline"
              className="cursor-pointer"
              onClick={() => navigate("/recipes")}
              disabled={loading || recordingStatus === "processing"}
            >
              Annuler
            </Button>

            {!audioFile && !isRecording && recordingStatus !== "processing" && !loading && (
              <Button
                variant="default"
                className="cursor-pointer"
                onClick={startRecording}
              >
                <Mic className="mr-2 h-4 w-4" />
                Commencer l'enregistrement
              </Button>
            )}

            {isRecording && (
              <Button
                variant="destructive"
                className="cursor-pointer"
                onClick={stopRecording}
              >
                <motion.div
                  className="flex items-center"
                  animate={{ scale: [1, 1.05, 1] }}
                  transition={{ repeat: Number.POSITIVE_INFINITY, duration: 1.5 }}
                >
                  <Mic className="mr-2 h-4 w-4" />
                  Arrêter l'enregistrement
                </motion.div>
              </Button>
            )}

            {audioFile && !isRecording && recordingStatus !== "processing" && !loading && (
              <Button
                className="cursor-pointer"
                onClick={handleSubmit}
              >
                <Upload className="mr-2 h-4 w-4" />
                Créer la recette
              </Button>
            )}

            {loading && (
              <Button
                className="cursor-pointer"
                disabled
              >
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Création en cours...
              </Button>
            )}
          </CardFooter>
        </Card>
      </div>
    </div >
  )
}

