"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card } from "@/components/ui/card"
import { CheckCircle2, Upload, ChevronRight, ChevronLeft } from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { createBrowserClient } from "@/lib/supabase/client"
import { useSearchParams } from "next/navigation"

type Step = 1 | 2 | 3 | 4

interface Course {
  id: string
  title: string
  modality: string
  shift: string
}

export function EnrollmentStepper() {
  const searchParams = useSearchParams()
  const [currentStep, setCurrentStep] = useState<Step>(1)
  const [courses, setCourses] = useState<Course[]>([])
  const [availableModalities, setAvailableModalities] = useState<string[]>([])
  const [availableShifts, setAvailableShifts] = useState<string[]>([])
  const [referralCode, setReferralCode] = useState("")
  const [referralCodeValid, setReferralCodeValid] = useState<boolean | null>(null)
  const [referralCodeChecking, setReferralCodeChecking] = useState(false)

  const [formData, setFormData] = useState({
    fullName: "",
    cpf: "",
    birthDate: "",
    email: "",
    phone: "",
    course: "",
    modality: "",
    shift: "",
    campus: "",
    acceptTerms: false,
    documents: [] as File[],
  })
  const [isComplete, setIsComplete] = useState(false)

  useEffect(() => {
    const refParam = searchParams.get("ref")
    if (refParam) {
      setReferralCode(refParam.toUpperCase())
      validateReferralCode(refParam.toUpperCase())
    }
  }, [searchParams])

  useEffect(() => {
    async function loadCourses() {
      const supabase = createBrowserClient()
      const { data, error } = await supabase.from("courses").select("id, title, modality, shift").order("title")

      if (error) {
        console.error("[v0] Error loading courses:", error)
        return
      }

      if (data) {
        console.log("[v0] Loaded courses:", data)
        setCourses(data)

        const modalities = [...new Set(data.map((c) => c.modality))]
        const shifts = [...new Set(data.map((c) => c.shift))]

        setAvailableModalities(modalities)
        setAvailableShifts(shifts)
      }
    }

    loadCourses()
  }, [])

  useEffect(() => {
    if (formData.course) {
      const selectedCourse = courses.find((c) => c.id === formData.course)
      if (selectedCourse) {
        const filteredModalities = courses.filter((c) => c.title === selectedCourse.title).map((c) => c.modality)
        setAvailableModalities([...new Set(filteredModalities)])
      }
    } else {
      const allModalities = [...new Set(courses.map((c) => c.modality))]
      setAvailableModalities(allModalities)
    }
  }, [formData.course, courses])

  useEffect(() => {
    if (formData.course && formData.modality) {
      const selectedCourse = courses.find((c) => c.id === formData.course)
      if (selectedCourse) {
        const filteredShifts = courses
          .filter((c) => c.title === selectedCourse.title && c.modality === formData.modality)
          .map((c) => c.shift)
        setAvailableShifts([...new Set(filteredShifts)])
      }
    } else if (formData.course) {
      const selectedCourse = courses.find((c) => c.id === formData.course)
      if (selectedCourse) {
        const filteredShifts = courses.filter((c) => c.title === selectedCourse.title).map((c) => c.shift)
        setAvailableShifts([...new Set(filteredShifts)])
      }
    } else {
      const allShifts = [...new Set(courses.map((c) => c.shift))]
      setAvailableShifts(allShifts)
    }
  }, [formData.course, formData.modality, courses])

  async function validateReferralCode(code: string) {
    if (!code) {
      setReferralCodeValid(null)
      return
    }

    setReferralCodeChecking(true)
    const supabase = createBrowserClient()

    const { data, error } = await supabase
      .from("referral_codes")
      .select("code, is_active")
      .eq("code", code.toUpperCase())
      .eq("is_active", true)
      .single()

    if (error || !data) {
      setReferralCodeValid(false)
    } else {
      setReferralCodeValid(true)
    }

    setReferralCodeChecking(false)
  }

  function handleReferralCodeChange(value: string) {
    const upperValue = value.toUpperCase()
    setReferralCode(upperValue)

    if (upperValue.length >= 3) {
      const timer = setTimeout(() => {
        validateReferralCode(upperValue)
      }, 500)
      return () => clearTimeout(timer)
    } else {
      setReferralCodeValid(null)
    }
  }

  const steps = [
    { number: 1, title: "Dados Pessoais" },
    { number: 2, title: "Curso Desejado" },
    { number: 3, title: "Documentos" },
    { number: 4, title: "Confirmação" },
  ]

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData((prev) => ({ ...prev, [name]: value }))
  }

  const handleSelectChange = (name: string, value: string) => {
    setFormData((prev) => ({ ...prev, [name]: value }))
  }

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setFormData((prev) => ({
        ...prev,
        documents: Array.from(e.target.files || []),
      }))
    }
  }

  /*const handleNext = () => {
    if (currentStep < 4) {
      setCurrentStep((currentStep + 1) as Step)
      localStorage.setItem("enrollmentData", JSON.stringify(formData))
    }
  }*/

    const handleNext = () => {
  // validações por passo
  if (currentStep === 1) {
    if (!isStep1Valid) {
      alert("Preencha todos os dados pessoais.")
      return
    }
  }

  if (currentStep === 2) {
    if (!formData.course || !formData.modality || !formData.shift || !formData.campus) {
      alert("Selecione o curso, modalidade, turno e unidade.")
      return
    }
  }

  if (currentStep < 4) {
    setCurrentStep((currentStep + 1) as Step)
    localStorage.setItem("enrollmentData", JSON.stringify(formData))
  }
}


    const handlePrevious = () => {
    if (currentStep > 1) {
      setCurrentStep((currentStep - 1) as Step)
    }
  }

  const isStep1Valid =
  formData.fullName.trim() !== "" &&
  formData.cpf.trim() !== "" &&
  formData.birthDate.trim() !== "" &&
  formData.email.trim() !== "" &&
  formData.phone.trim() !== ""


  const handleSubmit = async () => {

    if (!formData.birthDate) {
  alert("Preencha a data de nascimento.")
  return
}

if (!formData.course) {
  alert("Selecione um curso.")
  return
}
if (!formData.modality || !formData.shift || !formData.campus) {
  alert("Selecione modalidade, turno e unidade.")
  return
}


    const supabase = createBrowserClient()

    // 1) salva matrícula e pega o id
    const { data: enrollmentRows, error: enrollmentError } = await supabase
      .from("enrollments")
      .insert({
        full_name: formData.fullName,
        cpf: formData.cpf,
        birth_date: formData.birthDate ? formData.birthDate : null,

        email: formData.email,
        phone: formData.phone,
        course_id: formData.course,
        modality: formData.modality,
        shift: formData.shift,
        campus: formData.campus,
        status: "pending",
        referral_code: referralCodeValid ? referralCode : null,
      })
      .select("id")
      .single()

    if (enrollmentError || !enrollmentRows?.id) {
      console.error("[v0] Error saving enrollment:", enrollmentError)
      alert("Erro ao salvar matrícula. Por favor, tente novamente.")
      return
    }

    const enrollmentId = enrollmentRows.id as string

    // 2) upload dos arquivos no Storage
    if (formData.documents.length > 0) {
      const uploads = await Promise.all(
        formData.documents.map(async (file) => {
          const safeName = file.name.replace(/[^\w.\-]+/g, "_")
          const path = `${enrollmentId}/${crypto.randomUUID()}-${safeName}`

          const { error: uploadError } = await supabase.storage
            .from("enrollment-documents")
            .upload(path, file, { contentType: file.type, upsert: false })

          if (uploadError) return { ok: false as const, file, uploadError }
          return { ok: true as const, file, path }
        })
      )

      const failed = uploads.filter((u) => !u.ok)
      if (failed.length > 0) {
        console.error("[v0] Upload failed:", failed)
        alert("Matrícula salva, mas houve erro ao enviar um ou mais documentos.")
      }

      const okUploads = uploads.filter((u) => u.ok)
      if (okUploads.length > 0) {
        const { error: docsError } = await supabase.from("enrollment_documents").insert(
          okUploads.map((u) => ({
            enrollment_id: enrollmentId,
            file_name: u.file.name,
            storage_path: u.path,
            mime_type: u.file.type,
            size_bytes: u.file.size,
          }))
        )

        if (docsError) {
          console.error("[v0] Error saving document rows:", docsError)
          alert("Matrícula salva, mas não foi possível registrar os documentos no banco.")
        }
      }
    }

    // opcional: incrementa indicação
    if (referralCodeValid && referralCode) {
      await supabase.rpc("increment_referral_uses", { ref_code: referralCode })
    }

    setIsComplete(true)
    localStorage.removeItem("enrollmentData")
  }


  /*const handleSubmit = async () => {
    const supabase = createBrowserClient()

    const { data, error } = await supabase
      .from("enrollments")
      .insert({
        full_name: formData.fullName,
        cpf: formData.cpf,
        birth_date: formData.birthDate,
        email: formData.email,
        phone: formData.phone,
        course_id: formData.course,
        modality: formData.modality,
        shift: formData.shift,
        campus: formData.campus,
        status: "pending",
        referral_code: referralCodeValid ? referralCode : null,
      })
      .select()

    if (error) {
      console.error("[v0] Error saving enrollment:", error)
      alert("Erro ao salvar matrícula. Por favor, tente novamente.")
      return
    }

    if (referralCodeValid && referralCode) {
      await supabase.rpc("increment_referral_uses", { ref_code: referralCode })
    }

    console.log("[v0] Enrollment saved successfully:", data)
    setIsComplete(true)
    localStorage.removeItem("enrollmentData")
  }*/

  const getCourseName = () => {
    const course = courses.find((c) => c.id === formData.course)
    return course?.title || "-"
  }

  const formatDisplayText = (text: string) => {
    if (text === "ead") return "EAD"
    if (text === "semipresencial") return "Semipresencial"
    return text.charAt(0).toUpperCase() + text.slice(1)
  }

  const uniqueCourses = courses.reduce((acc, course) => {
    if (!acc.find((c) => c.title === course.title)) {
      acc.push(course)
    }
    return acc
  }, [] as Course[])

  if (isComplete) {
    return (
      <section className="py-16 bg-background">
        <div className="container mx-auto px-4">
          <Card className="max-w-2xl mx-auto p-12 border-2 border-primary/20 bg-primary/5 animate-scale-in">
            <div className="text-center space-y-6">
              <div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mx-auto">
                <CheckCircle2 className="h-10 w-10 text-primary" />
              </div>
              <div className="space-y-3">
                <h2 className="text-4xl font-bold">Matrícula confirmada!</h2>
                <p className="text-lg text-muted-foreground text-pretty">
                  Parabéns! Sua matrícula foi realizada com sucesso. Em breve você receberá um e-mail com as próximas
                  instruções.
                </p>
              </div>
              <div className="pt-4">
                <Button size="lg" onClick={() => (window.location.href = "/")}>
                  Voltar para o início
                </Button>
              </div>
            </div>
          </Card>
        </div>
      </section>
    )
  }

  return (
    <section className="py-16 bg-background">
      <div className="container mx-auto px-4">
        <div className="max-w-4xl mx-auto">
          <div className="mb-12">
            <div className="flex justify-between items-center relative">
              <div className="absolute top-5 left-0 right-0 h-1 bg-muted -z-10">
                <div
                  className="h-full bg-primary transition-all duration-500"
                  style={{ width: `${((currentStep - 1) / 3) * 100}%` }}
                />
              </div>

              {steps.map((step) => (
                <div key={step.number} className="flex flex-col items-center">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center font-bold transition-all duration-300 ${
                      step.number <= currentStep
                        ? "bg-primary text-primary-foreground"
                        : "bg-muted text-muted-foreground"
                    }`}
                  >
                    {step.number < currentStep ? <CheckCircle2 className="h-5 w-5" /> : step.number}
                  </div>
                  <span className="text-xs font-medium mt-2 text-center max-w-[100px] text-balance">{step.title}</span>
                </div>
              ))}
            </div>
          </div>

          <Card className="p-8 border-2">
            {currentStep === 1 && (
              <div className="space-y-6 animate-fade-in-up">
                <div>
                  <h2 className="text-2xl font-bold mb-2">Dados Pessoais</h2>
                  <p className="text-muted-foreground">Preencha seus dados pessoais para começar</p>
                </div>

                <div className="grid gap-5">
                  <div className="space-y-2">
                    <Label htmlFor="fullName">Nome completo *</Label>
                    <Input
                      id="fullName"
                      name="fullName"
                      value={formData.fullName}
                      onChange={handleInputChange}
                      placeholder="Digite seu nome completo"
                    />
                  </div>

                  <div className="grid sm:grid-cols-2 gap-5">
                    <div className="space-y-2">
                      <Label htmlFor="cpf">CPF *</Label>
                      <Input
                        id="cpf"
                        name="cpf"
                        value={formData.cpf}
                        onChange={handleInputChange}
                        placeholder="000.000.000-00"
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="birthDate">Data de nascimento *</Label>
                      <Input
                        id="birthDate"
                        name="birthDate"
                        type="date"
                        value={formData.birthDate}
                        onChange={handleInputChange}
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="email">E-mail *</Label>
                    <Input
                      id="email"
                      name="email"
                      type="email"
                      value={formData.email}
                      onChange={handleInputChange}
                      placeholder="seu@email.com"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="phone">Telefone *</Label>
                    <Input
                      id="phone"
                      name="phone"
                      value={formData.phone}
                      onChange={handleInputChange}
                      placeholder="(00) 00000-0000"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="referralCode">
                      Código de Indicação (opcional)
                      {referralCodeValid === true && <span className="text-green-600 ml-2">✓ Código válido</span>}
                      {referralCodeValid === false && <span className="text-red-600 ml-2">✗ Código inválido</span>}
                    </Label>
                    <Input
                      id="referralCode"
                      value={referralCode}
                      onChange={(e) => handleReferralCodeChange(e.target.value)}
                      placeholder="Digite o código de indicação"
                      maxLength={20}
                      disabled={referralCodeChecking}
                    />
                    <p className="text-xs text-muted-foreground">
                      Foi indicado por alguém? Insira o código de indicação aqui.
                    </p>
                  </div>
                </div>
              </div>
            )}

            {currentStep === 2 && (
              <div className="space-y-6 animate-fade-in-up">
                <div>
                  <h2 className="text-2xl font-bold mb-2">Curso Desejado</h2>
                  <p className="text-muted-foreground">Selecione o curso e a modalidade de ensino</p>
                </div>

                <div className="grid gap-5">
                  <div className="space-y-2">
                    <Label htmlFor="course">Curso *</Label>
                    <Select value={formData.course} onValueChange={(value) => handleSelectChange("course", value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecione o curso" />
                      </SelectTrigger>
                      <SelectContent>
                        {uniqueCourses.length > 0 ? (
                          uniqueCourses.map((course) => (
                            <SelectItem key={course.id} value={course.id}>
                              {course.title}
                            </SelectItem>
                          ))
                        ) : (
                          <SelectItem value="none" disabled>
                            Nenhum curso disponível
                          </SelectItem>
                        )}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="grid sm:grid-cols-2 gap-5">
                    <div className="space-y-2">
                      <Label htmlFor="modality">Modalidade *</Label>
                      <Select
                        value={formData.modality}
                        onValueChange={(value) => handleSelectChange("modality", value)}
                        disabled={!formData.course}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Selecione" />
                        </SelectTrigger>
                        <SelectContent>
                          {availableModalities.length > 0 ? (
                            availableModalities.map((modality) => (
                              <SelectItem key={modality} value={modality}>
                                {formatDisplayText(modality)}
                              </SelectItem>
                            ))
                          ) : (
                            <SelectItem value="none" disabled>
                              Selecione um curso primeiro
                            </SelectItem>
                          )}
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="shift">Turno *</Label>
                      <Select
                        value={formData.shift}
                        onValueChange={(value) => handleSelectChange("shift", value)}
                        disabled={!formData.modality}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Selecione" />
                        </SelectTrigger>
                        <SelectContent>
                          {availableShifts.length > 0 ? (
                            availableShifts.map((shift) => (
                              <SelectItem key={shift} value={shift}>
                                {formatDisplayText(shift)}
                              </SelectItem>
                            ))
                          ) : (
                            <SelectItem value="none" disabled>
                              Selecione a modalidade primeiro
                            </SelectItem>
                          )}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="campus">Unidade *</Label>
                    <Select value={formData.campus} onValueChange={(value) => handleSelectChange("campus", value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="Selecione a unidade" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ipora">Campus Iporá</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>
            )}

            {currentStep === 3 && (
              <div className="space-y-6 animate-fade-in-up">
                <div>
                  <h2 className="text-2xl font-bold mb-2">Documentos</h2>
                  <p className="text-muted-foreground">Faça upload dos documentos necessários</p>
                </div>

                <Card className="border-2 border-dashed p-8">
                  <div className="text-center space-y-4">
                    <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mx-auto">
                      <Upload className="h-8 w-8 text-primary" />
                    </div>
                    <div>
                      <h3 className="font-semibold mb-1">Envie seus documentos</h3>
                      <p className="text-sm text-muted-foreground">Formatos aceitos: PDF ou imagens (JPG, PNG)</p>
                    </div>
                    <div>
                      <Input
                        type="file"
                        multiple
                        accept=".pdf,.jpg,.jpeg,.png"
                        onChange={handleFileUpload}
                        className="cursor-pointer"
                      />
                    </div>
                    {formData.documents.length > 0 && (
                      <div className="pt-4 border-t">
                        <p className="text-sm font-medium mb-2">
                          {formData.documents.length} arquivo(s) selecionado(s)
                        </p>
                        <div className="space-y-1">
                          {formData.documents.map((file, index) => (
                            <p key={index} className="text-xs text-muted-foreground">
                              {file.name}
                            </p>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </Card>

                <div className="bg-muted/50 rounded-lg p-4">
                  <h4 className="font-semibold text-sm mb-2">Documentos necessários:</h4>
                  <ul className="text-sm text-muted-foreground space-y-1 list-disc list-inside">
                    <li>RG (frente e verso)</li>
                    <li>CPF</li>
                    <li>Comprovante de residência</li>
                    <li>Histórico escolar</li>
                    <li>Certificado de conclusão</li>
                  </ul>
                </div>
              </div>
            )}

            {currentStep === 4 && (
              <div className="space-y-6 animate-fade-in-up">
                <div>
                  <h2 className="text-2xl font-bold mb-2">Confirmação</h2>
                  <p className="text-muted-foreground">Revise seus dados antes de finalizar</p>
                </div>

                <div className="space-y-4">
                  <Card className="p-6 bg-muted/30">
                    <h3 className="font-semibold mb-3">Dados Pessoais</h3>
                    <div className="grid gap-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Nome:</span>
                        <span className="font-medium">{formData.fullName || "-"}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">CPF:</span>
                        <span className="font-medium">{formData.cpf || "-"}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">E-mail:</span>
                        <span className="font-medium">{formData.email || "-"}</span>
                      </div>
                    </div>
                  </Card>

                  <Card className="p-6 bg-muted/30">
                    <h3 className="font-semibold mb-3">Curso Selecionado</h3>
                    <div className="grid gap-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Curso:</span>
                        <span className="font-medium">{getCourseName()}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Modalidade:</span>
                        <span className="font-medium">{formatDisplayText(formData.modality) || "-"}</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">Turno:</span>
                        <span className="font-medium">{formatDisplayText(formData.shift) || "-"}</span>
                      </div>
                    </div>
                  </Card>

                  <Card className="p-6 bg-muted/30">
                    <h3 className="font-semibold mb-3">Documentos</h3>
                    <p className="text-sm text-muted-foreground">{formData.documents.length} documento(s) anexado(s)</p>
                  </Card>
                </div>

                <div className="flex items-start gap-3 p-4 bg-muted/50 rounded-lg">
                  <Checkbox
                    id="terms"
                    checked={formData.acceptTerms}
                    onCheckedChange={(checked) => setFormData((prev) => ({ ...prev, acceptTerms: checked as boolean }))}
                  />
                  <div className="space-y-1">
                    <Label htmlFor="terms" className="cursor-pointer font-medium">
                      Aceito os termos e condições *
                    </Label>
                    <p className="text-xs text-muted-foreground">
                      Li e concordo com os termos de matrícula e política de privacidade da Uniporá.
                    </p>
                  </div>
                </div>
              </div>
            )}

            <div className="flex items-center justify-between pt-6 mt-6 border-t">
              <Button
                variant="outline"
                onClick={handlePrevious}
                disabled={currentStep === 1}
                className="gap-2 bg-transparent"
              >
                <ChevronLeft className="h-4 w-4" />
                Voltar
              </Button>

              {currentStep < 4 ? (
                <Button
  onClick={handleNext}
  className="gap-2"
  disabled={currentStep === 1 && !isStep1Valid}
>
  Próximo
  <ChevronRight className="h-4 w-4" />
</Button>

              ) : (
                <Button onClick={handleSubmit} disabled={!formData.acceptTerms} className="gap-2">
                  Finalizar matrícula
                  <CheckCircle2 className="h-4 w-4" />
                </Button>
              )}
            </div>
          </Card>
        </div>
      </div>
    </section>
  )
}
