import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Chip,
  Box,
  Typography,
  Paper,
} from "@mui/material";
import { useDispatch } from "react-redux";
import { provinceSubmitDashboardNewsService } from "../../services/province-dashboard-submit-news";
import { AppContext } from "../../../../contexts/AppContext";
import { styled } from "@mui/material/styles";

const roles = [
  { id: 1, role: "AdminX", name: "ادمین ایکس" },
  { id: 2, role: "SuperAdmin", name: "ادمین کل" },
  { id: 3, role: "ProvinceOperator", name: "مدیر اجرایی" },
];

const StyledPaper = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(4),
  borderRadius: theme.shape.borderRadius * 2,
  boxShadow: theme.shadows[4],
  maxWidth: 800,
  margin: "0 auto",
}));

const StyledButton = styled(Button)(({ theme }) => ({
  marginTop: theme.spacing(3),
  padding: theme.spacing(1.5),
  fontSize: "1rem",
}));

export const ProvinceDashboardNews = () => {
  const [formData, setFormData] = useState({
    title: "",
    text: "",
    status: "",
    selectedRoles: [],
  });
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleRoleChange = (event) => {
    const selectedValues = event.target.value;
    setFormData((prev) => ({
      ...prev,
      selectedRoles: Array.isArray(selectedValues)
        ? selectedValues
        : [selectedValues],
    }));
  };

  const handleSubmit = () => {
    const payload = {
      role: formData.selectedRoles.map((role) => role.role),
      title: formData.title,
      text: formData.text,
      status: formData.status,
    };

    dispatch(provinceSubmitDashboardNewsService(payload)).then((response) => {
      if (response.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: response.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
        setFormData({
          title: "",
          text: "",
          status: "",
          selectedRoles: [],
        });
      }
    });
  };

  return (
    <Box sx={{ padding: 3 }}>
      <StyledPaper>
        <Typography variant="h5" gutterBottom sx={{ mb: 3, fontWeight: 600 }}>
          ایجاد اطلاعیه جدید
        </Typography>

        <Grid container spacing={3}>
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="عنوان"
              name="title"
              value={formData.title}
              onChange={handleChange}
              variant="outlined"
              size="small"
            />
          </Grid>

          <Grid item xs={12}>
            <TextField
              fullWidth
              label="متن توضیحات خبر"
              name="text"
              value={formData.text}
              onChange={handleChange}
              variant="outlined"
              multiline
              rows={6}
              size="small"
            />
          </Grid>

          <Grid item xs={12} sm={6}>
            <TextField
              fullWidth
              label="وضعیت"
              name="status"
              value={formData.status}
              onChange={handleChange}
              variant="outlined"
              size="small"
              placeholder="مثلاً: فوری، عادی، اطلاعیه"
            />
          </Grid>

          <Grid item xs={12} sm={6}>
            <FormControl fullWidth size="small">
              <InputLabel id="roles-label">نقش ها</InputLabel>
              <Select
                labelId="roles-label"
                id="roles-select"
                multiple
                value={formData.selectedRoles}
                onChange={handleRoleChange}
                renderValue={(selected) => (
                  <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
                    {selected.map((role) => (
                      <Chip key={role.id} label={role.name} size="small" />
                    ))}
                  </Box>
                )}
              >
                {roles.map((role) => (
                  <MenuItem key={role.id} value={role}>
                    {role.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          <Grid item xs={12} sx={{ textAlign: "left" }}>
            <StyledButton
              onClick={handleSubmit}
              color="primary"
              variant="contained"
              disabled={
                !formData.title ||
                !formData.text ||
                !formData.status ||
                formData.selectedRoles.length === 0
              }
            >
              ثبت اطلاعیه
            </StyledButton>
          </Grid>
        </Grid>
      </StyledPaper>
    </Box>
  );
};
