"use client"

import type React from "react"
import {
  Box,
  Typography,
  FormControl,
  FormControlLabel,
  Checkbox,
  FormHelperText,
  Button,
  Rating,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Paper,
  Divider,
} from "@mui/material"
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns"
import { styled } from "@mui/material/styles"
import fr from "date-fns/locale/fr"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faChevronDown, faCloudUpload } from "@fortawesome/free-solid-svg-icons"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { FieldType, type FormulaireChamp } from "@/shared/types/formulaire"
import SvgColor from "@/shared/components/svg-color"
import { StyledTextField, StyledMenuItem, StyledDatePicker } from "@/shared/theme/css"

// Styled components
const VisuallyHiddenInput = styled("input")({
  clip: "rect(0 0 0 0)",
  clipPath: "inset(50%)",
  height: 1,
  overflow: "hidden",
  position: "absolute",
  bottom: 0,
  left: 0,
  whiteSpace: "nowrap",
  width: 1,
})

export const CustomDateIcon = ({ isReadOnly }: { isReadOnly?: boolean }) => (
  <SvgColor
    src="/assets/icons/ic_date.svg"
    sx={{
      color: isReadOnly ? "text.disabled" : "primary.main",
      width: 18,
      mr: "6px",
    }}
  />
)

interface FieldRendererProps {
  field: FormulaireChamp
  value: any
  onChange: (fieldId: string, value: any) => void
  error?: string
  fileInputRef?: React.RefObject<HTMLInputElement>
  handleFileClick?: (fieldId: string) => void
}

export const FieldRenderer: React.FC<FieldRendererProps> = ({
  field,
  value,
  onChange,
  error,
  fileInputRef,
  handleFileClick,
}) => {
  switch (field.type) {
    case FieldType.TEXT:
    case FieldType.EMAIL:
    case FieldType.NUMBER:
    case FieldType.PHONE:
      return (
        <Box>
          <StyledTextField
            fullWidth
            id={field.id}
            label={field.label}
            placeholder={
              field.placeholder ||
              `Saisir ${field.type === "TEXT" ? "le texte" : field.type === "NUMBER" ? "un nombre" : field.type === "EMAIL" ? "l'email" : "le numéro"}`
            }
            type={field.type}
            value={value || ""}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(field.id, e.target.value)}
            required={field.required}
            error={!!error}
            helperText={error}
            variant="outlined"
            InputLabelProps={{
              shrink: true,
            }}
            sx={{ "& .MuiOutlinedInput-root": { borderRadius: "4px" }, mb: 2 }}
          />
        </Box>
      )

    case FieldType.TEXTAREA:
      return (
        <Box>
          <StyledTextField
            fullWidth
            id={field.id}
            label={field.label}
            placeholder={field.placeholder || "Saisir plusieurs lignes de texte"}
            multiline
            rows={4}
            value={value || ""}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(field.id, e.target.value)}
            required={field.required}
            error={!!error}
            helperText={error}
            variant="outlined"
            InputLabelProps={{
              shrink: true,
            }}
            sx={{ "& .MuiOutlinedInput-root": { borderRadius: "4px" }, mb: 2 }}
          />
        </Box>
      )

    case FieldType.SELECT:
      return (
        <Box>
          <StyledTextField
            select
            fullWidth
            id={field.id}
            label={field.label}
            value={value || ""}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(field.id, e.target.value)}
            required={field.required}
            error={!!error}
            helperText={error}
            variant="outlined"
            InputLabelProps={{
              shrink: true,
            }}
            placeholder="Sélectionner"
            SelectProps={{
              displayEmpty: true,
              renderValue: (selectedValue: any) => {
                if (!selectedValue) return <Typography color="text.secondary">Sélectionner</Typography>
                const option = field.options?.find((opt) => opt.value === selectedValue)
                return <Typography>{option?.label || String(selectedValue)}</Typography>
              },
            }}
            sx={{ "& .MuiOutlinedInput-root": { borderRadius: "4px" }, mb: 2 }}
          >
            {(field.options || []).map((option) => (
              <StyledMenuItem key={option.value} value={option.value}>
                {option.label}
              </StyledMenuItem>
            ))}
          </StyledTextField>
        </Box>
      )

    case FieldType.DATE:
      return (
        <Box>
          <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
            <StyledDatePicker
              label={field.label}
              views={["year", "month", "day"]}
              slots={{
                openPickerIcon: () => <CustomDateIcon />,
              }}
              openTo="year"
              value={value ? new Date(value) : null}
              onChange={(date) => onChange(field.id, date?.toISOString() || '')}
              slotProps={{
                textField: (params: any) => ({
                  ...params,
                  fullWidth: true,
                  placeholder: "DD/MM/YYYY",
                  InputLabelProps: {
                    shrink: true,
                  },
                  required: field.required,
                  error: !!error,
                  helperText: error,
                  id: field.id,
                }),
                actionBar: {
                  actions: ["clear", "today"],
                },
              }}
            />
          </LocalizationProvider>
        </Box>
      )

    case FieldType.FILE:
      return (
        <Box>
          <Button
            variant="outlined"
            startIcon={<FontAwesomeIcon icon={faCloudUpload} />}
            onClick={() => (handleFileClick ? handleFileClick(field.id) : null)}
            sx={{
              bgcolor: "#f5f7ff",
              color: "#6366F1",
              borderColor: "#e0e3ff",
              "&:hover": {
                bgcolor: "#eceefe",
                borderColor: "#d1d4fc",
              },
              textTransform: "uppercase",
              fontWeight: "bold",
              py: 1,
            }}
          >
            CHOISIR UN FICHIER
            {!handleFileClick ? (
              <VisuallyHiddenInput
                type="file"
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  const file = e.target.files?.[0]
                  onChange(field.id, file)
                }}
              />
            ):<></>}
          </Button>
          <ConditionalComponent isValid={!!value}>
            <Typography variant="body2" sx={{ mt: 1 }}>
              Fichier sélectionné: {typeof value === "object" && value !== null ? value.name : value}
            </Typography>
          </ConditionalComponent>
          <ConditionalComponent isValid={!!error}>
            <FormHelperText error>{error}</FormHelperText>
          </ConditionalComponent>
        </Box>
      )

    case FieldType.RATING:
      return (
        <Box>
          <Typography variant="subtitle1" sx={{ mb: 1, fontWeight: 500 }}>
            {field.label}{" "}
            <ConditionalComponent isValid={!!field.required}>
              <span style={{ color: "#d32f2f" }}>*</span>
            </ConditionalComponent>
          </Typography>
          <Rating name={field.id} value={Number(value) || 0} onChange={(_, newValue) => onChange(field.id, newValue)} />
          <ConditionalComponent isValid={!!error}>
            <FormHelperText error>{error}</FormHelperText>
          </ConditionalComponent>
        </Box>
      )

    case FieldType.CONSENT:
      return (
        <FormControl required={field.required} error={!!error}>
          <FormControlLabel
            control={
              <Checkbox
                checked={!!value}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => onChange(field.id, e.target.checked)}
              />
            }
            label={
              <Typography>
                {field.label}{" "}
                <ConditionalComponent isValid={!!field.required}>
                  <span style={{ color: "#d32f2f" }}>*</span>
                </ConditionalComponent>
              </Typography>
            }
          />
          <ConditionalComponent isValid={!!error}>
            <FormHelperText>{error}</FormHelperText>
          </ConditionalComponent>
        </FormControl>
      )

    case FieldType.SECTION:
      return (
        <Paper
          variant={field.sectionStyle === "outlined" ? "outlined" : "elevation"}
          elevation={field.sectionStyle === "card" ? 2 : 0}
          sx={{
            p: 2,
            mb: 2,
            bgcolor: field.sectionStyle === "filled" ? "action.hover" : "background.paper",
          }}
        >
          {field.sectionTitle ? (
            <Typography variant="h6" gutterBottom>
              {field.sectionTitle}
            </Typography>
          ):<></>}
          {field.sectionDescription ? (
            <Typography variant="body2" color="text.secondary" paragraph>
              {field.sectionDescription}
            </Typography>
          ):<></>}
        </Paper>
      )

    default:
      return null
  }
}

interface SectionRendererProps {
  section: FormulaireChamp
  sectionFields: FormulaireChamp[]
  formValues: Record<string, any>
  errors: Record<string, string>
  onChange: (fieldId: string, value: any) => void
  fileInputRef?: React.RefObject<HTMLInputElement>
  handleFileClick?: (fieldId: string) => void
}

export const SectionRenderer: React.FC<SectionRendererProps> = ({
  section,
  sectionFields,
  formValues,
  errors,
  onChange,
  fileInputRef,
  handleFileClick,
}) => {
  const sectionStyle = section.sectionStyle || "default"
  const isCollapsible = !!section.sectionCollapsible
  const isCollapsed = isCollapsible && !!section.sectionCollapsed
  const columns = section.columns || 1

  const sectionContent = (
    <>
      <ConditionalComponent isValid={!!section.sectionDescription}>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
          {section.sectionDescription}
        </Typography>
      </ConditionalComponent>

      <Box sx={{ display: "grid", gridTemplateColumns: `repeat(${columns}, 1fr)`, gap: 2 }}>
        {sectionFields.map((field) => (
          <Box key={field.id}>
            <FieldRenderer
              field={field}
              value={formValues[field.id]}
              onChange={onChange}
              error={errors[field.id]}
              fileInputRef={fileInputRef}
              handleFileClick={handleFileClick}
            />
          </Box>
        ))}
      </Box>
    </>
  )

  // Section styling
  const sectionProps = {
    sx: {
      p: 3,
      mb: 3,
      ...(sectionStyle === "filled" && {
        bgcolor: "grey.50",
      }),
      ...(sectionStyle === "outlined" && {
        border: "2px solid",
        borderColor: "primary.light",
        borderRadius: 1,
      }),
      ...(sectionStyle === "card" && {
        boxShadow: 2,
        borderRadius: 1,
      }),
    },
  }

  return (
    <ConditionalComponent
      isValid={!!section.sectionCollapsible}
      defaultComponent={
        <Box {...sectionProps}>
          <Typography variant="h6" sx={{ mb: 2, pb: 1, borderBottom: "1px solid", borderColor: "divider" }}>
            {section.sectionTitle || section.label}
          </Typography>
          {sectionContent}
        </Box>
      }
    >
      <Accordion
        defaultExpanded={!isCollapsed}
        sx={{
          mb: 3,
          ...(sectionStyle === "card" && {
            boxShadow: 2,
          }),
          ...(sectionStyle === "outlined" && {
            border: "2px solid",
            borderColor: "primary.light",
            "&::before": {
              display: "none",
            },
          }),
        }}
      >
        <AccordionSummary
          expandIcon={<FontAwesomeIcon icon={faChevronDown} />}
          sx={{
            ...(sectionStyle === "filled" && {
              bgcolor: "grey.100",
            }),
          }}
        >
          <Typography variant="h6">{section.sectionTitle || section.label}</Typography>
        </AccordionSummary>
        <AccordionDetails>{sectionContent}</AccordionDetails>
      </Accordion>
    </ConditionalComponent>
  )
}