"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Loader2, Sparkles, Save, X, Upload } from "lucide-react"
import { cn } from "@/lib/utils"
import { supabase } from "@/lib/supabase"
import type { Database } from "@/lib/supabase"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select } from "@/components/ui/select"
import { toast } from "sonner"

type Trainer = Database["public"]["Tables"]["trainers"]["Row"]
type TrainerInsert = Database["public"]["Tables"]["trainers"]["Insert"]
type TrainerUpdate = Database["public"]["Tables"]["trainers"]["Update"]

interface TrainerFormProps {
  initialData?: Trainer
  mode?: "create" | "edit"
}

const SPECIALTY_OPTIONS = [
  { value: "Core", label: "Core" },
  { value: "Strength", label: "Strength" },
  { value: "Cardio", label: "Cardio" },
  { value: "Full Body", label: "Full Body" },
  { value: "Recovery", label: "Recovery" },
]

const PRESET_COLORS = [
  "#FF6B35", "#FFD60A", "#30D158", "#5AC8FA", "#BF5AF2",
  "#FF9500", "#FF2D55", "#5856D6", "#FF3B30", "#34C759",
]

export default function TrainerForm({ initialData, mode = "create" }: TrainerFormProps) {
  const router = useRouter()
  const [isLoading, setIsLoading] = useState(false)
  const [isGenerating, setIsGenerating] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [generatedImages, setGeneratedImages] = useState<{ buffer: Buffer; url?: string }[]>([])
  const [selectedImage, setSelectedImage] = useState<string | null>(null)
  const [generatingPrompt, setGeneratingPrompt] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [avatarFile, setAvatarFile] = useState<File | null>(null)

  const [name, setName] = useState(initialData?.name || "")
  const [specialty, setSpecialty] = useState(initialData?.specialty || "Core")
  const [color, setColor] = useState(initialData?.color || "#FF6B35")
  const [avatarUrl, setAvatarUrl] = useState(initialData?.avatar_url || "")

  const validate = () => {
    const newErrors: Record<string, string> = {}
    if (!name.trim()) newErrors.name = "Name is required"
    if (!specialty) newErrors.specialty = "Specialty is required"
    if (!color) newErrors.color = "Color is required"
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleGenerateImages = async () => {
    if (!name.trim()) {
      toast.error("Please enter a name first")
      return
    }

    const prompt = generatingPrompt ||
      `Professional portrait photo of ${name}, fitness trainer, friendly smile, gym setting, high quality, facing camera directly, energetic and professional`

    setIsGenerating(true)
    try {
      const trainerId = initialData?.id || "new-trainer"
      const filename = `avatar_${Date.now()}.png`

      const response = await fetch('/api/ai/generate-avatar', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt, trainerId, filename }),
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || 'Generation failed')
      }

      const { url } = await response.json()

      const savedImages = [{ buffer: Buffer.alloc(0), url }]
      setGeneratedImages(savedImages)
      setSelectedImage(url)
      setAvatarUrl(url)
      toast.success('Avatar generated')
    } catch (err) {
      console.error("Generation failed:", err)
      toast.error(err instanceof Error ? err.message : "Failed to generate images")
    } finally {
      setIsGenerating(false)
    }
  }

  const handleSelectGenerated = (url: string) => {
    setSelectedImage(url)
    setAvatarUrl(url)
    setAvatarFile(null)
  }

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setAvatarFile(file)
    setSelectedImage(null)

    setIsUploading(true)
    try {
      const trainerId = initialData?.id || "new-trainer"
      const filename = `upload_${Date.now()}.png`
      const path = `${trainerId}/${filename}`

      const { error } = await supabase.storage
        .from('trainer-avatars')
        .upload(path, file, {
          contentType: file.type,
          upsert: true,
        })

      if (error) throw new Error(error.message)

      const { data: { publicUrl } } = supabase.storage
        .from('trainer-avatars')
        .getPublicUrl(path)

      setAvatarUrl(publicUrl)
      setGeneratedImages([])
      toast.success("Avatar uploaded")
    } catch (err) {
      console.error("Upload failed:", err)
      toast.error(err instanceof Error ? err.message : "Failed to upload avatar")
    } finally {
      setIsUploading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validate()) return

    setIsLoading(true)
    try {
      const trainerData = {
        name: name.trim(),
        specialty,
        color,
        avatar_url: avatarUrl || null,
        workout_count: initialData?.workout_count || 0,
      }

      let result
      if (mode === "edit" && initialData) {
        result = await (supabase
          .from("trainers") as any)
          .update(trainerData)
          .eq("id", initialData.id)
          .select()
          .single()
      } else {
        result = await (supabase
          .from("trainers") as any)
          .insert(trainerData)
          .select()
          .single()
      }

      if (result.error) throw result.error

      toast.success(mode === "edit" ? "Trainer updated" : "Trainer created")
      router.push("/trainers")
    } catch (err) {
      console.error("Failed to save:", err)
      toast.error("Failed to save trainer")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      <div className="space-y-4">
        <h2 className="text-lg font-semibold text-white">Basic Information</h2>

        <div className="grid gap-4">
          <div className="space-y-2">
            <Label htmlFor="name">Name *</Label>
            <Input
              id="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g., Félia"
              className={cn(errors.name && "border-red-500")}
            />
            {errors.name && <p className="text-xs text-red-500">{errors.name}</p>}
          </div>

          <div className="space-y-2">
            <Label htmlFor="specialty">Specialty *</Label>
            <Select
              id="specialty"
              value={specialty}
              onValueChange={setSpecialty}
              options={SPECIALTY_OPTIONS}
            />
          </div>

          <div className="space-y-2">
            <Label>Color</Label>
            <div className="flex gap-2 flex-wrap">
              {PRESET_COLORS.map((c) => (
                <button
                  key={c}
                  type="button"
                  onClick={() => setColor(c)}
                  className={cn(
                    "w-8 h-8 rounded-full border-2 transition-all",
                    color === c ? "border-white scale-110" : "border-transparent"
                  )}
                  style={{ backgroundColor: c }}
                />
              ))}
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="w-8 h-8 rounded-full cursor-pointer"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="space-y-4">
        <h2 className="text-lg font-semibold text-white">Trainer Avatar</h2>

        <div className="space-y-2">
          <Label>Generate with AI (Nano Banana Pro)</Label>
          <div className="flex gap-2">
            <Input
              value={generatingPrompt}
              onChange={(e) => setGeneratingPrompt(e.target.value)}
              placeholder={`Portrait of ${name || 'trainer'}, fitness, friendly...`}
              className="flex-1"
            />
            <Button
              type="button"
              onClick={handleGenerateImages}
              disabled={isGenerating || !name.trim()}
              className="bg-purple-500 hover:bg-purple-600"
            >
              {isGenerating ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Sparkles className="w-4 h-4" />
              )}
              Generate
            </Button>
          </div>
        </div>

        {generatedImages.length > 0 && (
          <div className="space-y-2">
            <Label>Select Generated Image</Label>
            <div className="grid grid-cols-3 gap-4">
              {generatedImages.map((img, i) => (
                <div
                  key={i}
                  onClick={() => img.url && handleSelectGenerated(img.url)}
                  className={cn(
                    "relative aspect-square rounded-lg overflow-hidden cursor-pointer border-2 transition-all",
                    selectedImage === img.url ? "border-orange-500 scale-105" : "border-transparent hover:border-neutral-600"
                  )}
                >
                  {img.url && <img src={img.url} alt={`Generated ${i + 1}`} className="w-full h-full object-cover" />}
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="space-y-2">
          <Label>Or Upload Custom Image</Label>
          <div className="flex items-center gap-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => document.getElementById('avatar-upload')?.click()}
              disabled={isUploading}
              className="border-neutral-700"
            >
              {isUploading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Upload className="w-4 h-4" />
              )}
              Choose File
            </Button>
            <input
              id="avatar-upload"
              type="file"
              accept="image/jpeg,image/png,image/webp"
              onChange={handleFileChange}
              className="hidden"
            />
            {avatarFile && <span className="text-sm text-neutral-400">{avatarFile.name}</span>}
          </div>
        </div>

        {avatarUrl && (
          <div className="space-y-2">
            <Label>Current Avatar</Label>
            <div className="relative w-32 h-32">
              <img
                src={avatarUrl}
                alt="Current avatar"
                className="w-full h-full object-cover rounded-full border-2 border-neutral-700"
              />
              {selectedImage === avatarUrl && (
                <div className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full">
                  <Sparkles className="w-8 h-8 text-orange-500" />
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      <div className="flex justify-end gap-3 pt-4 border-t border-neutral-800">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.back()}
          className="border-neutral-700"
        >
          Cancel
        </Button>
        <Button type="submit" disabled={isLoading} className="bg-orange-500 hover:bg-orange-600">
          {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
          {mode === "edit" ? "Update Trainer" : "Create Trainer"}
        </Button>
      </div>
    </form>
  )
}
