"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { recipeService } from "@/api/recipe"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Mic, ArrowLeft, Trash2, ChefHat, Info, X, Check } from "lucide-react"
import { motion, AnimatePresence } from "framer-motion"
import { KitchenIllustration } from "@/components/illustrations/KitchenIllustration"
import { CookingLoader } from "@/components/illustrations/CookingLoader"
import { useAudioRecorder } from "@/hooks/useAudioRecorder"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { cn } from "@/lib/utils"
import { useMobile } from "@/hooks/useMobile"

export default function RecipeForm() {
  const navigate = useNavigate()
  const isMobile = useMobile()

  const {
    isLoading: isRecorderLoading,
    isRecording,
    currentRecording,
    startRecording,
    stopRecording,
  } = useAudioRecorder()

  const [audioFile, setAudioFile] = useState<File | null>(null)
  const [recordingStatus, setRecordingStatus] = useState<"idle" | "recording" | "processing">("idle")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [recordingTime, setRecordingTime] = useState(0)
  const [showTips, setShowTips] = useState(false)

  // Update audioFile when recording is available
  useEffect(() => {
    if (currentRecording) {
      fetch(currentRecording)
        .then((res) => res.blob())
        .then((blob) => {
          const file = new File([blob], "recording.mp3", { type: "audio/mp3" })
          setAudioFile(file)
          setRecordingStatus("idle")
          setError("")
        })
    }
  }, [currentRecording])

  // Recording timer
  useEffect(() => {
    let interval: NodeJS.Timeout | null = null
    if (isRecording) {
      interval = setInterval(() => {
        setRecordingTime((prev) => prev + 1)
      }, 1000)
    } else {
      setRecordingTime(0)
    }
    return () => {
      if (interval) clearInterval(interval)
    }
  }, [isRecording])

  // Handle recording start
  const handleStartRecording = async () => {
    try {
      await startRecording()
      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.")
    }
  }

  // Handle recording stop
  const handleStopRecording = async () => {
    if (isRecording) {
      await stopRecording()
      setRecordingStatus("processing")
      // Processing will be updated to "idle" when the audioFile is set
    }
  }

  // Fonction pour réinitialiser l'enregistrement
  const handleResetRecording = () => {
    setAudioFile(null)
    setRecordingStatus("idle")
    setError("")
  }

  // 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)
    }
  }

  // Format recording time
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`
  }

  return (
    <div className="min-h-screen flex flex-col bg-gradient-to-b from-amber-50 to-orange-50 dark:from-slate-950 dark:to-slate-900">
      {/* Header */}
      <header className="sticky top-0 z-10 backdrop-blur-sm bg-amber-50/80 dark:bg-slate-950/80 border-b border-amber-100 dark:border-slate-800 p-4 flex justify-between items-center">
        <Button variant="ghost" size="icon" className="rounded-full" onClick={() => navigate("/recipes")}>
          <ArrowLeft className="h-5 w-5" />
          <span className="sr-only">Retour</span>
        </Button>
        <h1 className="text-lg font-medium">Nouvelle Recette</h1>
        <Sheet>
          <SheetTrigger asChild>
            <Button variant="ghost" size="icon" className="rounded-full">
              <Info className="h-5 w-5" />
              <span className="sr-only">Aide</span>
            </Button>
          </SheetTrigger>
          <SheetContent side="bottom" className="rounded-t-xl">
            <SheetHeader>
              <SheetTitle>Comment ça marche ?</SheetTitle>
              <SheetDescription>
                <ol className="mt-4 space-y-3 list-decimal list-inside text-sm">
                  <li>Appuyez sur le bouton d'enregistrement</li>
                  <li>Listez clairement les ingrédients que vous avez à disposition</li>
                  <li>Terminez l'enregistrement</li>
                  <li>Notre IA créera une recette adaptée à vos ingrédients</li>
                </ol>
              </SheetDescription>
            </SheetHeader>
          </SheetContent>
        </Sheet>
      </header>

      <main className="flex-1 flex flex-col">
        {/* Main content */}
        <div className="flex-1 flex flex-col p-4 max-w-md mx-auto w-full">
          {/* Illustration */}
          <AnimatePresence>
            {!isRecording && !loading && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className="flex justify-center mb-6"
              >
                <KitchenIllustration height={120} />
              </motion.div>
            )}
          </AnimatePresence>

          {/* Error message */}
          <AnimatePresence>
            {error && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: "auto" }}
                exit={{ opacity: 0, height: 0 }}
                className="mb-4"
              >
                <div className="rounded-lg bg-red-50 p-3 text-sm text-red-700 dark:bg-red-900/30 dark:text-red-200 flex items-start">
                  <div className="flex-1">{error}</div>
                  <Button variant="ghost" size="sm" className="h-6 w-6 p-0 rounded-full" onClick={() => setError("")}>
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Recording UI */}
          <AnimatePresence mode="wait">
            {recordingStatus === "processing" || loading ? (
              <motion.div
                key="processing"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="flex-1 flex flex-col items-center justify-center"
              >
                <CookingLoader />
                <h2 className="mt-6 text-xl font-medium text-center">Préparation en cours...</h2>
                <p className="text-sm text-muted-foreground text-center mt-2 max-w-xs">
                  Notre chef IA mijote quelque chose de délicieux avec vos ingrédients
                </p>
              </motion.div>
            ) : isRecording ? (
              <motion.div
                key="recording"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="flex-1 flex flex-col"
              >
                <Card className="flex-1 flex flex-col items-center justify-center p-6 border-2 border-red-400 dark:border-red-700 bg-gradient-to-b from-red-50 to-red-100 dark:from-red-950/30 dark:to-red-900/20">
                  <motion.div
                    animate={{ scale: [1, 1.1, 1] }}
                    transition={{ repeat: Number.POSITIVE_INFINITY, duration: 1.5 }}
                    className="relative"
                  >
                    <div className="absolute inset-0 bg-red-400/20 dark:bg-red-700/30 rounded-full animate-ping" />
                    <div className="relative bg-red-500 dark:bg-red-600 text-white p-6 rounded-full">
                      <Mic className="h-8 w-8" />
                    </div>
                  </motion.div>

                  <div className="mt-8 text-center">
                    <div className="text-3xl font-mono font-bold text-red-600 dark:text-red-400">
                      {formatTime(recordingTime)}
                    </div>
                    <p className="mt-2 text-sm text-red-700 dark:text-red-300 animate-pulse">
                      Enregistrement en cours...
                    </p>
                  </div>

                  <div className="mt-8 w-full max-w-xs">
                    <Button variant="destructive" className="w-full" size="lg" onClick={handleStopRecording}>
                      Arrêter l'enregistrement
                    </Button>
                  </div>
                </Card>

                <div className="mt-4">
                  <Button variant="outline" className="w-full text-sm" onClick={() => setShowTips(!showTips)}>
                    {showTips ? "Masquer les conseils" : "Afficher les conseils"}
                  </Button>

                  <AnimatePresence>
                    {showTips && (
                      <motion.div
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: "auto" }}
                        exit={{ opacity: 0, height: 0 }}
                        className="overflow-hidden"
                      >
                        <div className="mt-3 p-3 bg-amber-100/50 dark:bg-amber-900/20 rounded-lg text-sm">
                          <h3 className="font-medium mb-2">Conseils pour un bon enregistrement :</h3>
                          <ul className="space-y-2 list-disc list-inside text-muted-foreground">
                            <li>Parlez clairement et lentement</li>
                            <li>Listez un ingrédient à la fois</li>
                            <li>Précisez les quantités si possible</li>
                            <li>Mentionnez vos préférences culinaires</li>
                          </ul>
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              </motion.div>
            ) : audioFile ? (
              <motion.div
                key="review"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="flex-1 flex flex-col"
              >
                <Card className="flex-1 p-5 border-2 border-green-200 dark:border-green-800 bg-gradient-to-b from-green-50 to-green-100/50 dark:from-green-950/30 dark:to-green-900/20">
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2">
                      <div className="bg-green-100 dark:bg-green-800 p-2 rounded-full">
                        <Check className="h-5 w-5 text-green-600 dark:text-green-300" />
                      </div>
                      <h3 className="font-medium text-green-700 dark:text-green-300">Enregistrement prêt !</h3>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8 text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-full"
                      onClick={handleResetRecording}
                    >
                      <Trash2 className="h-4 w-4" />
                      <span className="sr-only">Supprimer</span>
                    </Button>
                  </div>

                  <div className="bg-white/80 dark:bg-slate-800/50 rounded-lg p-3 mb-4">
                    <audio controls className="w-full h-10">
                      <source src={URL.createObjectURL(audioFile)} type={audioFile.type} />
                      Votre navigateur ne supporte pas la lecture audio.
                    </audio>
                    <p className="text-xs text-muted-foreground mt-2">
                      {audioFile.name} ({(audioFile.size / 1024).toFixed(1)} KB)
                    </p>
                  </div>

                  <div className="mt-auto">
                    <Button className="w-full" size="lg" onClick={handleSubmit}>
                      <ChefHat className="h-5 w-5 mr-2" />
                      Créer ma recette
                    </Button>
                  </div>
                </Card>

                <div className="mt-4 text-center">
                  <Button variant="outline" onClick={handleResetRecording}>
                    Nouvel enregistrement
                  </Button>
                </div>
              </motion.div>
            ) : (
              <motion.div
                key="start"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="flex-1 flex flex-col"
              >
                <div className="text-center mb-6">
                  <h2 className="text-xl font-medium">Qu'avez-vous dans votre frigo ?</h2>
                  <p className="text-sm text-muted-foreground mt-2">
                    Enregistrez les ingrédients que vous avez à disposition
                  </p>
                </div>

                <Card
                  className={cn(
                    "flex-1 flex flex-col items-center justify-center p-6",
                    "bg-gradient-to-b from-amber-100/50 to-orange-100/30",
                    "dark:from-amber-900/20 dark:to-orange-900/10",
                    "border-2 border-dashed border-amber-200 dark:border-amber-800",
                  )}
                >
                  <motion.div
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    className="cursor-pointer"
                    onClick={handleStartRecording}
                  >
                    <div className="bg-gradient-to-br from-amber-400 to-orange-500 dark:from-amber-500 dark:to-orange-600 p-6 rounded-full text-white shadow-lg">
                      <Mic className="h-10 w-10" />
                    </div>
                  </motion.div>

                  <h3 className="mt-6 text-lg font-medium">Appuyez pour commencer</h3>
                  <p className="text-sm text-muted-foreground text-center mt-2 max-w-xs">
                    Listez les ingrédients que vous avez à disposition et notre IA créera une recette adaptée
                  </p>

                  <Button className="mt-8" size="lg" onClick={handleStartRecording}>
                    Commencer l'enregistrement
                  </Button>
                </Card>

                <div className="mt-6 bg-amber-100/50 dark:bg-amber-900/20 rounded-lg p-4">
                  <h3 className="font-medium mb-2 flex items-center gap-2">
                    <Info className="h-4 w-4" />
                    Comment ça marche ?
                  </h3>
                  <ol className="space-y-2 list-decimal list-inside text-sm text-muted-foreground">
                    <li>Enregistrez les ingrédients que vous avez</li>
                    <li>Notre IA analyse votre enregistrement</li>
                    <li>Recevez une recette personnalisée</li>
                    <li>Cuisinez et régalez-vous !</li>
                  </ol>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </main>
    </div>
  )
}

