import React, { useState } from "react";
import { Box, Button, Divider, Typography, Paper, IconButton } from "@mui/material";
import { Add, Delete } from "@mui/icons-material";
import EducationForm, { EducationFormState, educationInitialValues } from "./EducationForm";

export default function EducationSection({ 
    applicantId, 
    onChange 
}: { 
    applicantId: string, 
    onChange: (educations: EducationFormState[]) => void 
}) {
  const [educations, setEducations] = useState<EducationFormState[]>([
    { ...educationInitialValues, applicantId }
  ]);

  // افزودن یک فرم جدید
  const addEducation = () => {
    setEducations((prev) => [...prev, { ...educationInitialValues, applicantId }]);
  };

  // حذف یک فرم از لیست
  const removeEducation = (index: number) => {
    setEducations((prev) => prev.filter((_, i) => i !== index));
  };

  // به‌روزرسانی محتوای یک فرم خاص
  const updateEducation = (index: number, data: EducationFormState) => {
    const nextList = [...educations];
    nextList[index] = data;
    setEducations(nextList);
    onChange(nextList); // ارسال لیست نهایی به کامپوننت اصلی
  };

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 3 }}>
      <Typography variant="h6" sx={{ color: "#1e293b", fontWeight: 700 }}>
        سوابق تحصیلی
      </Typography>

      {educations.map((ed, index) => (
        <Paper key={index} sx={{ p: 3, borderRadius: "16px", border: "1px solid #e2e8f0", position: "relative" }}>
          
          {/* دکمه حذف برای هر آیتم */}
          {educations.length > 1 && (
            <IconButton 
              onClick={() => removeEducation(index)} 
              sx={{ position: "absolute", top: 8, right: 8, color: "#ef4444" }}
            >
              <Delete />
            </IconButton>
          )}

          <Typography variant="subtitle2" sx={{ mb: 2, color: "#64748b" }}>
            مدرک تحصیلی {index + 1}
          </Typography>

          <EducationForm 
            value={ed} 
            onChange={(newData) => updateEducation(index, newData)} 
            applicantId={applicantId}
          />
        </Paper>
      ))}

      <Button
        variant="contained"
        startIcon={<Add />}
        onClick={addEducation}
        sx={{
          borderRadius: "12px",
          backgroundColor: "#2563eb",
          py: 1.5,
          textTransform: "none",
          fontWeight: 600
        }}
      >
        افزودن مدرک تحصیلی جدید
      </Button>
    </Box>
  );
}
