import React from "react";
import { Box, Button } from "@mui/material";
import { WorkExperienceFormItem, WorkExperienceItemForm } from "./WorkExperienceForm";

export interface WorkExperienceSectionProps {
  value: WorkExperienceFormItem[];
  onChange: (next: WorkExperienceFormItem[]) => void;
}

const emptyItem = (): WorkExperienceFormItem => ({
  hasNoExperience: false,
  companyName: "",
  lastPosition: "",
  startYear: "",
  endYear: "",
  leavingReason: "",
  description: "",
});

export function WorkExperienceSection({ value, onChange }: WorkExperienceSectionProps) {
  
  // رفع خطا: ایجاد تابع ایمن برای جلوگیری از "undefined is not a function"
  const safeOnChange = (next: WorkExperienceFormItem[]) => {
    if (typeof onChange === "function") {
      onChange(next);
    } else {
      console.error("onChange is missing in WorkExperienceSection parent!");
    }
  };

  const items = value && value.length > 0 ? value : [emptyItem()];

  const handleAddItem = () => {
    safeOnChange([...items, emptyItem()]);
  };

  const handleRemoveItem = (index: number) => {
    const next = items.filter((_, i) => i !== index);
    safeOnChange(next.length > 0 ? next : [emptyItem()]);
  };

  const handleItemChange = (index: number, nextItem: WorkExperienceFormItem) => {
    // منطق اصلی: اگر یک آیتم "فاقد سابقه" شد، لیست باید فقط شامل همان یک آیتم باشد
    if (nextItem.hasNoExperience) {
      safeOnChange([nextItem]);
    } else {
      const nextItems = items.map((it, i) => (i === index ? nextItem : it));
      safeOnChange(nextItems);
    }
  };

  const hasNoExperienceSelected = items.some((x) => x.hasNoExperience);

  return (
    <Box sx={{ display: "grid", gap: 2 }}>
      {items.map((item, idx) => (
        <WorkExperienceItemForm
          key={idx}
          index={idx}
          value={item}
          onChange={(next:any) => handleItemChange(idx, next)}
          onRemove={() => handleRemoveItem(idx)}
          disableRemove={items.length === 1}
        />
      ))}

      <Box sx={{ display: "flex", justifyContent: "flex-end" }}>
        <Button variant="outlined" onClick={handleAddItem} disabled={hasNoExperienceSelected}>
          افزودن سابقه کاری
        </Button>
      </Box>
    </Box>
  );
}
