"use client";
import React, { useState } from "react";
import {
  Box,
  Button,
  Typography,
  Paper,
  Container,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import IdentityForm from "./forms/identity/IdentityForm";
import PersonalInfoForm from "./forms/personal/PersonalInfoForm";
import PhysicalInfoForm from "./forms/physicalInfo/PhysicalInfoForm";

import SkillsForm from "./forms/skillsForm/SkillsForm";
import JobInfoForm from "./forms/jobInfo/JobInfoForm";
import RelationsForm from "./forms/relation/RelationForm";
import RegistrationCenterForm from "./forms/register-center/RegistrationCenterForm";
import { INITIAL_WIZARD_DATA, WizardFormData } from "@/core/types";
import EducationForm from "./forms/education/EducationForm";
import CourseForm from "./forms/course/CourseForm";
import JobRequestForm from "./forms/jobRequest/JobRequestForm";
import WorkExperienceForm from "./forms/workExperience/WorkExperienceForm";
import ReferralForm from "./forms/referral/ReferralForm";
import { useSearchParams } from "next/navigation";

// کامپوننت پیش‌فرض برای مراحلی که هنوز نساختید
const PlaceholderStep = ({ step }: any) => (
  <Typography color="text.secondary">
    محتوای مرحله {step} در حال طراحی است...
  </Typography>
);

// --- ۲. نگاشت (Mapping) مراحل به کامپوننت‌ها ---

const STEP_COMPONENTS: Record<number, React.ComponentType<any>> = {
  1: RegistrationCenterForm,
  2: IdentityForm,
  3: PersonalInfoForm,
  4: PhysicalInfoForm,
  5: EducationForm,
  6: JobRequestForm,
  7: CourseForm,
  8: SkillsForm,
  9: WorkExperienceForm,
  10: JobInfoForm,
  11: ReferralForm,
  12: RelationsForm,
  // بقیه مراحل از Placeholder استفاده می‌کنند
};

const STEP_LABELS = [
  "انتخاب مركز",
  "مشخصات هويتي",
  "مشخصات فردي",
  "مشخصات ظاهري",
  "مشخصات تحصيلي",
  "شغل درخواستي",
  "دوره هاي آموزشي",
  "مهارت ها",
  "سوابق كاري",
  "اطلاعات كاري",
  "معرف",
  "مشخصات آشنايان",
];

// --- ۳. کامپوننت اصلی استپر ---

export default function MultiStepForm() {
  const searchParams = useSearchParams();

  // خواندن مرحله از URL (اگر نبود، پیش‌فرض ۱)
  const initialStep = Number(searchParams.get("step")) || 1;
  const [activeStep, setActiveStep] = useState(initialStep);
  const [maxStepReached, setMaxStepReached] = useState(initialStep);
  const [formData, setFormData] = useState<WizardFormData>(() => {
    // اگر می‌خواهی بعد از رفرش دیتا نپرد، اینجا از localStorage بخون
    return INITIAL_WIZARD_DATA;
  });

  const updateFormData = (patch: Partial<WizardFormData>) => {
    setFormData((prev) => ({ ...prev, ...patch }));
  };

  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));

  const ActiveStepComponent = STEP_COMPONENTS[activeStep] || PlaceholderStep;

  return (
    <Box
      sx={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        bgcolor: "#f8fafc",
        py: 4,
      }}
    >
      <Container maxWidth="xl">
        <div
          style={{
            display: "flex",
            flexDirection: isMobile ? "column" : "row",
            gap: "40px",
          }}
        >
          {/* Sidebar Navigation */}
          {!isMobile && (
            <div style={{ width: "200px", flexShrink: 0 }}>
              <Typography
                variant="h5"
                sx={{ fontWeight: 900, mb: 4, color: "#1e293b" }}
              >
                مراحل فرم
              </Typography>
              {STEP_LABELS.map((label, i) => (
                <Box
                  key={i}
                  onClick={() =>
                    i + 1 <= maxStepReached && setActiveStep(i + 1)
                  }
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    mb: 2,
                    cursor: i + 1 <= maxStepReached ? "pointer" : "not-allowed",
                    opacity: i + 1 <= maxStepReached ? 1 : 0.4,
                    color: i + 1 === activeStep ? "#2563eb" : "#64748b",
                    transition: "0.2s",
                  }}
                >
                  <Box
                    sx={{
                      width: 32,
                      height: 32,
                      borderRadius: "10px",
                      mr: 2,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      bgcolor:
                        i + 1 === activeStep
                          ? "#2563eb"
                          : i + 1 < activeStep
                            ? "#4CAF5033"
                            : "#f1f5f9",
                      color: i + 1 === activeStep ? "#fff" : "#2563eb",
                      fontWeight: 700,
                      fontSize: "0.8rem",
                      border:
                        i + 1 === activeStep ? "none" : "1px solid #e2e8f0",
                    }}
                  >
                    {i + 1 < activeStep ? (
                      <CheckCircleIcon sx={{ fontSize: 18 }} color="success" />
                    ) : (
                      Number(i + 1).toLocaleString("fa-IR")
                    )}
                  </Box>
                  <Typography
                    variant="body2"
                    sx={{
                      fontWeight: i + 1 === activeStep ? 800 : 500,
                      color: i + 1 < activeStep ? "green" : "",
                    }}
                  >
                    {label}
                  </Typography>
                </Box>
              ))}
            </div>
          )}

          {/* Main Form Area */}
          <div style={{ flexGrow: 1 }}>
            <Paper
              sx={{
                p: { xs: 3, md: 6 },
                borderRadius: "35px",
                boxShadow: "0 25px 50px -12px rgba(0,0,0,0.05)",
                border: "1px solid #e2e8f0",
              }}
            >
              <Box sx={{ mb: 4 }}>
                <Typography
                  variant="overline"
                  sx={{ color: "#2563eb", fontWeight: 900 }}
                >
                  مرحله {activeStep.toLocaleString("fa-IR")} از{" "}
                  {STEP_LABELS.length.toLocaleString("fa-IR")}
                </Typography>
                <Typography
                  variant="h4"
                  sx={{ fontWeight: 900, color: "#0f172a" }}
                >
                  {STEP_LABELS[activeStep - 1]}
                </Typography>
              </Box>

              {/* رندر شدن داینامیک کامپوننت مرحله فعلی */}
              <div className="w-full">
                <ActiveStepComponent
                  data={formData} // کل دیتای فرم
                  update={updateFormData} // تابع آپدیت‌کننده
                  step={activeStep}
                  setStep={setActiveStep}
                />
              </div>
            </Paper>
          </div>
        </div>
      </Container>
    </Box>
  );
}
