import React from "react";
import {
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Typography,
  IconButton,
} from "@mui/material";
import {
  ExpandMore as ExpandMoreIcon,
  Delete as DeleteIcon,
} from "@mui/icons-material";
import { GuildInfoSection } from "./GuildInfoSection";

export const GuildInfoAccordionItem = ({
  guildIndex,
  guildData,
  guildActive,
  isAdmin,
  isSuperAdmin,
  cities,
  typeActivities,
  onDelete,
  canDelete,
  guildFormValues,
  onGuildValuesChange,
  expanded,
  onChange,
  mainFormik,
}) => {
  // Errors and touched for this guild from main formik (formik.errors.guilds[i], formik.touched.guilds[i])
  const guildErrors = mainFormik?.errors?.guilds?.[guildIndex] ?? {};
  const guildTouched = mainFormik?.touched?.guilds?.[guildIndex] ?? {};

  // Create a formik-like object for this guild's values
  const guildFormik = {
    values: guildFormValues || {},
    setFieldValue: (fieldName, value) => {
      onGuildValuesChange(guildIndex, fieldName, value);
    },
    handleChange: (e) => {
      onGuildValuesChange(guildIndex, e.target.name, e.target.value);
    },
    handleBlur: (e) => {
      const name = e?.target?.name;
      if (name && mainFormik?.setFieldTouched) {
        mainFormik.setFieldTouched(`guilds.${guildIndex}.${name}`, true);
      }
    },
    errors: guildErrors,
    touched: guildTouched,
  };
  const getGuildTitle = () => {
    if (guildData?.guildsName) {
      return guildData.guildsName;
    }
    if (guildData?.title) {
      return guildData.title;
    }
    if (guildFormik.values.guild_name) {
      return guildFormik.values.guild_name;
    }
    return `واحد صنفی ${guildIndex + 1}`;
  };

  return (
    <Accordion expanded={expanded} onChange={onChange}>
      <AccordionSummary
        expandIcon={<ExpandMoreIcon />}
        sx={{
          "& .MuiAccordionSummary-content": {
            alignItems: "center",
            justifyContent: "space-between",
          },
        }}
      >
        <Typography variant="h6" sx={{ flexGrow: 1, fontSize: 18 }}>
          {getGuildTitle()}
        </Typography>
        {canDelete && (
          <IconButton
            onClick={(e) => {
              e.stopPropagation();
              onDelete();
            }}
            color="error"
            size="small"
            sx={{ mr: 1 }}
          >
            <DeleteIcon />
          </IconButton>
        )}
      </AccordionSummary>
      <AccordionDetails>
        <GuildInfoSection
          formik={guildFormik}
          guild={guildData}
          guildActive={guildActive}
          isAdmin={isAdmin}
          isSuperAdmin={isSuperAdmin}
          cities={cities}
          typeActivities={typeActivities}
          hideTitle={true}
          noGridWrapper={true}
          guildIndex={guildIndex}
        />
      </AccordionDetails>
    </Accordion>
  );
};
