"use client"

import React, { useState, useEffect } from "react"
import { Box, Paper, Typography, Grid, Button } from "@mui/material"
import type { IFormulaire } from "@/shared/types/formulaire"
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns"
import fr from "date-fns/locale/fr"
import { getSectionFields, getSections, getUnsectionedFields, isFieldVisible } from "../form-field/form-field-utils"
import { FieldRenderer, SectionRenderer } from "../form-field/field-renderer"
import { pxToRem } from "@/shared/theme/typography"

interface FormPreviewProps {
  formulaire: IFormulaire
}

export default function FormPreview({ formulaire }: FormPreviewProps) {
  const [formValues, setFormValues] = useState<Record<string, any>>({})
  const [errors, setErrors] = useState<Record<string, string>>({})

  // Initialize form values
  useEffect(() => {
    const initialValues: Record<string, any> = {}
    formulaire.fields.forEach((field) => {
      if (field.type === "checkbox") {
        initialValues[field.id] = field.defaultValue || []
      } else {
        initialValues[field.id] = field.defaultValue || ""
      }
    })
    setFormValues(initialValues)
  }, [formulaire])

  const handleInputChange = (fieldId: string, value: any) => {
    setFormValues((prev) => ({
      ...prev,
      [fieldId]: value,
    }))

    // Clear error for this field
    if (errors[fieldId]) {
      setErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors[fieldId]
        return newErrors
      })
    }
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()

    // Validate required fields
    const newErrors: Record<string, string> = {}

    formulaire.fields.forEach((field) => {
      if (field.required && isFieldVisible(field, formValues)) {
        const value = formValues[field.id]
        if (!value || (Array.isArray(value) && value.length === 0)) {
          newErrors[field.id] = "Ce champ est obligatoire"
        }
      }
    })

    setErrors(newErrors)

    if (Object.keys(newErrors).length === 0) {
      // Form is valid
      console.log("Form submitted:", formValues)
      alert("Formulaire soumis avec succès!")
    }
  }

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Box sx={{ p: 3 }}>
        <Paper elevation={0} sx={{ px: 4, maxWidth: "100%", margin: "0 auto" }}>
          <Typography  variant="h5" sx={{ 
              fontSize:  pxToRem(25),
              color: "primary.main",
              fontWeight: 700,
            mb: 1 }}>
            {formulaire.title}
          </Typography>

        <Typography variant="subtitle1" sx={{  mb: 2, fontWeight: (theme) => theme.typography.fontWeightSemiBold, }}>
            {formulaire.description}
          </Typography>

          <form onSubmit={handleSubmit}>
            {/* Render sections first */}
            {getSections(formulaire.fields).map((section) => (
              <React.Fragment key={section.id}>
                <SectionRenderer
                  section={section}
                  sectionFields={getSectionFields(section.id, formulaire.fields)}
                  formValues={formValues}
                  errors={errors}
                  onChange={handleInputChange}
                />
              </React.Fragment>
            ))}

            {/* Then render fields that don't belong to a section */}
            <Grid container spacing={3}>
              {getUnsectionedFields(formulaire.fields).map((field) => (
                <Grid item xs={12} key={field.id}>
                  {isFieldVisible(field, formValues) ? (
                    <FieldRenderer
                      field={field}
                      value={formValues[field.id]}
                      onChange={handleInputChange}
                      error={errors[field.id]}
                    />
                  ):<></>}
                </Grid>
              ))}
            </Grid>
          </form>
        </Paper>
      </Box>
    </LocalizationProvider>
  )
}
