import React from "react";
import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  FormGroup,
  InputLabel,
  MenuItem,
  Select,
  SelectChangeEvent,
  TextField,
} from "@mui/material";
import useFormModal from "../store/useFormModal";

const servicesList = ["United States", "India", "Both"];

function FormThreePSelling() {
  const { openModal } = useFormModal();

  //form
  const [brandOwner, setBrandOwner] =
    React.useState("");
  const [primaryLocation, setPrimaryLocation] = React.useState<string[]>([]);
  const [productCategory, setProductCategory] = React.useState<string[]>([]);
  const [currentSell, setCurrentSell] = React.useState<string[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [formData, setFormData] = React.useState({
    name: "",
    email: "",
    company: "",
    website: "",
    otherPrimeryProducts: "",
    otherMarketplace: "",
    numberOfSkus: "",
    marketPlaceStore: "",
  });
  

  const handleBrandOwnerChange = (
    event: SelectChangeEvent,
  ) => {
    setBrandOwner(event.target.value as string);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      [e.target.id || e.target.name]: e.target.value,
    });
  };

  const handleServiceChange = (primaryLocation: string) => {
    setPrimaryLocation(
      (prev) =>
        prev.includes(primaryLocation)
          ? prev.filter((service) => service !== primaryLocation) // Remove if already there
          : [...prev, primaryLocation], // Add if not there
    );
  };

  const handleProductCategoryChange = (productCategory: string) => {
    setProductCategory((prev) =>
      prev.includes(productCategory)
        ? prev.filter((curSell) => curSell !== productCategory)
        : [...prev, productCategory],
    );
  };

  const handleCurrentSellChange = (currentSellOption: string) => {
    setCurrentSell((prev) =>
      prev.includes(currentSellOption)
        ? prev.filter((curSell) => curSell !== currentSellOption)
        : [...prev, currentSellOption],
    );
  };

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const payload = {
      name: formData.name,
      email: formData.email,
      company: formData.company,
      website: formData.website,
      productCategory: productCategory,
      brandOwner: brandOwner,
      numberOfSkus: formData.numberOfSkus,
      currentsell: currentSell,
      marketPlaceStore: formData.marketPlaceStore,
      primaryLocation: primaryLocation,
      otherMarketplace: formData.otherMarketplace,
      otherPrimeryProducts: formData.otherPrimeryProducts,
    };

    try {
      const res = await fetch("/api/leadsThreePSelling", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

      if (!res.ok) throw new Error("Failed");
      openModal("thankyou");
      setFormData({
        name: "",
        email: "",
        company: "",
        website: "",
        otherPrimeryProducts: "",
        otherMarketplace: "",
        numberOfSkus: "",
        marketPlaceStore: "",
      });
      setBrandOwner("");
      setPrimaryLocation([]);
      setCurrentSell([]);
      setLoading(false);
    } catch (err) {
      alert("Failed to send form");
    } finally {
      setLoading(false);
    }
  };

  const textFieldStyle = {
    backgroundColor: "#f5f5f5",
    borderRadius: "50px",
    "& .MuiInputBase-root": {
      borderRadius: "55px",
    },
    "& .MuiInputLabel-root": {
      color: "#000", // default label color
    },
    "& .MuiInputLabel-root.Mui-focused": {
      color: "#000", // focused label color
    },
    "& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline": {
      borderColor: "#B1B1b1", // focused border colorB
      borderWidth: "2px",
    },
  };

  const checkboxStyle = {
    py: "2px !important",
    color: "#999",
    "&.Mui-checked": {
      color: "#000",
    },
  };

  const formLabelStyle = {
    "& .MuiFormControlLabel-label": {
      color: "#000", // ✅ label color
      fontSize: "14px",
    },
    "& .MuiTypography-root": {
      color: "#000", // ✅ fallback (important)
    },
  };

  return (
    <form onSubmit={handleFormSubmit}>
      <div className="flex flex-wrap">
        <div className="w-full mb-5">
          <p className="text-[20px] lg:text-[25px] font-semibold uppercase text-center">
            Contact Information
          </p>
        </div>
        <div className="w-full">
          <div className="mb-3">
            <TextField
              fullWidth
              id="name"
              label="Full Name"
              variant="outlined"
              size="small"
              value={formData.name}
              onChange={handleInputChange}
              required
              sx={textFieldStyle}
            />
          </div>
        </div>
        <div className="w-full lg:w-[50%] lg:pe-1.5">
          <div className="mb-3">
            <TextField
              fullWidth
              id="email"
              label="Work Email Address"
              variant="outlined"
              size="small"
              value={formData.email}
              onChange={handleInputChange}
              required
              sx={textFieldStyle}
            />
          </div>
        </div>
        <div className="w-full lg:w-[50%] lg:ps-1.5">
          <div className="mb-3">
            <TextField
              fullWidth
              id="company"
              label="Company / Brand Name"
              variant="outlined"
              size="small"
              value={formData.company}
              onChange={handleInputChange}
              required
              sx={textFieldStyle}
            />
          </div>
        </div>
        <div className="w-full">
          <div className="mb-3">
            <TextField
              fullWidth
              id="website"
              label="Website / E-commerce Marketplace Store Link"
              variant="outlined"
              size="small"
              value={formData.website}
              onChange={handleInputChange}
              sx={textFieldStyle}
            />
          </div>
        </div>

        <div className="w-full">
          {/* <p className="text-[20px] font-semibold my-2">
            BUSINESS & CHANNEL DETAILS
          </p> */}
          <p className="text-[17px] font-semibold mb-1">
            Primary Product Category*
          </p>
        </div>

        <div className="w-full">
          <div className="mb-2">
            <FormGroup>
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Toys")}
                    onChange={() => handleProductCategoryChange("Toys")}
                  />
                }
                label="Toys"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Pet Products")}
                    onChange={() => handleProductCategoryChange("Pet Products")}
                  />
                }
                label="Pet Products"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Home & Kitchen")}
                    onChange={() =>
                      handleProductCategoryChange("Home & Kitchen")
                    }
                  />
                }
                label="Home & Kitchen"
              />
              {/* <p className="text-[17px] font-semibold my-1">Primary Platforms</p> */}
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Beauty & Personal Care")}
                    onChange={() =>
                      handleProductCategoryChange("Beauty & Personal Care")
                    }
                  />
                }
                label="Beauty & Personal Care"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Electronics")}
                    onChange={() => handleProductCategoryChange("Electronics")}
                  />
                }
                label="Electronics"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Apparel")}
                    onChange={() => handleProductCategoryChange("Apparel")}
                  />
                }
                label="Apparel"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={productCategory.includes("Other")}
                    onChange={() => handleProductCategoryChange("Other")}
                  />
                }
                label="Other"
              />
              <div
                className={`my-3 ${productCategory.includes("Other") ? "block" : "hidden"}`}
              >
                <TextField
                  fullWidth
                  id="otherPrimeryProducts"
                  label="Other Primary Products"
                  variant="outlined"
                  size="small"
                  value={formData.otherPrimeryProducts}
                  onChange={handleInputChange}
                  sx={textFieldStyle}
                />
              </div>
            </FormGroup>
          </div>
        </div>

        <div className="w-full">
          <div className="mb-3">
            <p className="text-[17px] font-semibold mb-2">
              Are you the brand owner or an authorized distributor?
            </p>
            <FormControl fullWidth size="small">
              <InputLabel
                id="current-monthly-online-revenue"
                sx={{
                  color: "#000",
                  "&.Mui-focused": { color: "#000" },
                }}
              >
                Select
              </InputLabel>
              <Select
                labelId="current-monthly-online-revenue"
                id="current-monthly-online-revenue"
                value={brandOwner}
                label="Select"
                onChange={handleBrandOwnerChange}
                size="small"
                sx={{
                  borderRadius: "50px",
                  backgroundColor: "#f5f5f5",
                  "& .MuiInputBase-root": {
                    borderRadius: "50px",
                  },
                  "& .MuiInputBase-input": {
                    borderRadius: "50px",
                  },
                  "& .MuiOutlinedInput-notchedOutline": {
                    borderColor: "#ccc",
                  },
                  "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                    borderColor: "#ccc",
                    borderWidth: "2px",
                  },
                  "& .MuiSelect-icon": {
                    color: "#000",
                  },
                  "& .MuiSelect-select": {
                    color: "#000",
                  },
                }}
              >
                <MenuItem value="Brand Owner">Brand Owner</MenuItem>
                <MenuItem value="Authorized Distributor">
                  Authorized Distributor
                </MenuItem>
                <MenuItem value="Manufacturer">Manufacturer</MenuItem>
                <MenuItem value="Other">Other</MenuItem>
              </Select>
            </FormControl>
          </div>
        </div>

        <div className="w-full">
          <div className="mb-3">
            <TextField
              fullWidth
              id="numberOfSkus"
              label="Number of SKUs you want Eleantz to sell *"
              variant="outlined"
              size="small"
              value={formData.numberOfSkus}
              onChange={handleInputChange}
              sx={textFieldStyle}
            />
          </div>
        </div>

        <div className="w-full">
          <p className="text-[20px] font-semibold my-2">Marketplace Presence</p>
          <p className="text-[17px] font-semibold mb-1">
            Where are your products currently sold? *
          </p>
        </div>

        <div className="w-full">
          <div className="mb-2">
            <FormGroup>
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Amazon")}
                    onChange={() => handleCurrentSellChange("Amazon")}
                  />
                }
                label="Amazon"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Walmart")}
                    onChange={() => handleCurrentSellChange("Walmart")}
                  />
                }
                label="Walmart"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Brand Website / DTC")}
                    onChange={() =>
                      handleCurrentSellChange("Brand Website / DTC")
                    }
                  />
                }
                label="Brand Website / DTC"
              />
              {/* <p className="text-[17px] font-semibold my-1">Primary Platforms</p> */}
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Retail Stores")}
                    onChange={() => handleCurrentSellChange("Retail Stores")}
                  />
                }
                label="Retail Stores"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Not selling online yet")}
                    onChange={() =>
                      handleCurrentSellChange("Not selling online yet")
                    }
                  />
                }
                label="Not selling online yet"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Electronics")}
                    onChange={() => handleCurrentSellChange("Electronics")}
                  />
                }
                label="Electronics"
              />
              <FormControlLabel
                sx={formLabelStyle}
                control={
                  <Checkbox
                    sx={checkboxStyle}
                    checked={currentSell.includes("Other marketplaces")}
                    onChange={() =>
                      handleCurrentSellChange("Other marketplaces")
                    }
                  />
                }
                label="Other marketplaces"
              />
              <div
                className={`my-3 ${currentSell.includes("Other marketplaces") ? "block" : "hidden"}`}
              >
                <TextField
                  fullWidth
                  id="otherMarketplace"
                  label="Other Marketplaces"
                  variant="outlined"
                  size="small"
                  value={formData.otherMarketplace}
                  onChange={handleInputChange}
                  sx={textFieldStyle}
                />
              </div>
            </FormGroup>
          </div>
        </div>

        <div className="w-full">
          <div className="mb-3">
            <TextField
              fullWidth
              id="marketPlaceStore"
              label="Marketplace Store / Product Link"
              variant="outlined"
              size="small"
              value={formData.marketPlaceStore}
              onChange={handleInputChange}
              required
              sx={textFieldStyle}
            />
          </div>
        </div>

        <div className="w-full">
          <div className="mb-3">
            <p className="text-[17px] font-semibold mb-1">
              Primary fulfillment location *
            </p>
            <FormGroup>
              {servicesList.map((service) => (
                <div className="mb-0" key={service}>
                  <FormControlLabel
                    sx={formLabelStyle}
                    control={
                      <Checkbox
                        sx={checkboxStyle}
                        checked={primaryLocation.includes(service)}
                        onChange={() => handleServiceChange(service)}
                      />
                    }
                    label={service}
                  />
                </div>
              ))}
            </FormGroup>
          </div>
        </div>
        <div className="w-full">
          <div className="mb-3">
            <p className="text-[17px] font-semibold">Consent</p>
            <FormGroup>
              <FormControlLabel
                required
                sx={formLabelStyle}
                control={<Checkbox sx={checkboxStyle} />}
                label="I agree to be contacted by the Eleantz team regarding my growth audit and related insights."
              />
            </FormGroup>
          </div>
        </div>
        <div className="w-full">
          <div className="flex justify-center">
            <Button
              type="submit"
              variant="contained"
              sx={{
                padding: "10px 40px",
                fontSize: "16px",
                fontWeight: "bold",
                textTransform: "none",
                borderRadius: "50px",
                backgroundColor: "#c4262c",
              }}
              disabled={loading}
            >
              {loading ? "Submitting..." : "Get My Free Growth Audit"}
            </Button>
          </div>
          {/*  <small className="text-center text-gray-700 font-semibold block pt-2">
            Your information is yours, safe and confidential.
          </small> */}
        </div>
      </div>
    </form>
  );
}

export default FormThreePSelling;
