import React, { useState } from "react";
import {
  Box,
  TextField,
  Button,
  Typography,
  Paper,
  Alert,
  Grid,
  Stack,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
} from "@mui/material";
import axios from "axios";

const ReferralForm = () => {
  const [formData, setFormData] = useState({
    candidateName: "",
    email: "",
    mobile: "",
    experience: "",
    experienceOther: "",
    applyingFor: "",
    applyingForOther: "",
    relationship: "",
    relationshipOther: "",
    referredBy: {
      name: "",
      email: "",
    },
    resume: null,
  });

  const [message, setMessage] = useState({ type: "", text: "" });
  const [submitting, setSubmitting] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;

    if (name.startsWith("referredBy.")) {
      const field = name.split(".")[1];
      setFormData((prev) => ({
        ...prev,
        referredBy: {
          ...prev.referredBy,
          [field]: value,
        },
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setFormData((prev) => ({
        ...prev,
        resume: file,
      }));
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setMessage({ type: "", text: "" });

    try {
      // Determine final values to send for dropdowns with 'Other'
      const applyingForToSend =
        formData.applyingFor === "Other"
          ? formData.applyingForOther.trim()
          : formData.applyingFor;

      const relationshipToSend =
        formData.relationship === "Other"
          ? formData.relationshipOther.trim()
          : formData.relationship;

      const experienceToSend =
        formData.experience === "Other"
          ? formData.experienceOther.trim()
          : formData.experience;

      // Validate these required fields including others
      if (
        !formData.candidateName.trim() ||
        !formData.email.trim() ||
        !formData.mobile.trim() ||
        !applyingForToSend ||
        !relationshipToSend ||
        !experienceToSend ||
        !formData.referredBy.name.trim() ||
        !formData.referredBy.email.trim()
      ) {
        setMessage({ type: "error", text: "Please fill all required fields." });
        setSubmitting(false);
        return;
      }

      const formDataToSend = new FormData();
      formDataToSend.append("candidateName", formData.candidateName.trim());
      formDataToSend.append("email", formData.email.trim());
      formDataToSend.append("mobile", formData.mobile.trim());
      formDataToSend.append("applyingFor", applyingForToSend);
      formDataToSend.append("relationship", relationshipToSend);
      formDataToSend.append("experience", experienceToSend);
      formDataToSend.append("referredBy", JSON.stringify(formData.referredBy));

      if (formData.resume) {
        formDataToSend.append("resume", formData.resume);
      }

      await axios.post(
        "http://localhost:5000/api/referral/submit",
        formDataToSend,
        {
          headers: { "Content-Type": "multipart/form-data" },
        }
      );

      setMessage({
        type: "success",
        text: "Referral submitted successfully!",
      });

      setFormData({
        candidateName: "",
        email: "",
        mobile: "",
        experience: "",
        experienceOther: "",
        applyingFor: "",
        applyingForOther: "",
        relationship: "",
        relationshipOther: "",
        referredBy: {
          name: "",
          email: "",
        },
        resume: null,
      });
    } catch (error) {
      console.error("Error submitting referral:", error);
      const errorMsg =
        error.response?.data?.message ||
        "Error submitting referral. Please try again.";
      setMessage({ type: "error", text: errorMsg });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Box
      sx={{
        maxWidth: 720,
        mx: "auto",
        mt: 6,
        p: { xs: 2, sm: 4 },
        mb: 6,
      }}
    >
      <Paper elevation={4} sx={{ p: { xs: 3, sm: 5 } }}>
        <Typography variant="h4" fontWeight={600} mb={3} align="center">
          Submit Referral
        </Typography>

        {message.text && (
          <Alert
            severity={message.type}
            sx={{ mb: 3 }}
            onClose={() => setMessage({ type: "", text: "" })}
          >
            {message.text}
          </Alert>
        )}

        <form onSubmit={handleSubmit} noValidate>
          <Grid container spacing={3}>
            {/* Candidate Details */}
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="Candidate Name"
                name="candidateName"
                value={formData.candidateName}
                onChange={handleChange}
                required
                autoComplete="off"
                variant="outlined"
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="Candidate Email"
                name="email"
                type="email"
                value={formData.email}
                onChange={handleChange}
                required
                autoComplete="off"
                variant="outlined"
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="Mobile Number"
                name="mobile"
                value={formData.mobile}
                onChange={handleChange}
                required
                variant="outlined"
                inputProps={{ maxLength: 15 }}
                autoComplete="off"
              />
            </Grid>

            {/* Applying For */}
            <Grid item xs={12} sm={6}>
              <FormControl fullWidth required>
                <InputLabel id="applyingFor-label">Applying For</InputLabel>
                <Select
                  labelId="applyingFor-label"
                  label="Applying For"
                  name="applyingFor"
                  value={formData.applyingFor}
                  onChange={handleChange}
                >
                  <MenuItem value="LEGAL">LEGAL</MenuItem>
                  <MenuItem value="NON-LEGAL">NON-LEGAL</MenuItem>
                  <MenuItem value="Other">Other</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            {formData.applyingFor === "Other" && (
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="Specify Applying For"
                  name="applyingForOther"
                  value={formData.applyingForOther}
                  onChange={handleChange}
                  required
                  variant="outlined"
                  autoComplete="off"
                />
              </Grid>
            )}

            {/* Relationship */}
            <Grid item xs={12} sm={6}>
              <FormControl fullWidth required>
                <InputLabel id="relationship-label">Relationship</InputLabel>
                <Select
                  labelId="relationship-label"
                  label="Relationship"
                  name="relationship"
                  value={formData.relationship}
                  onChange={handleChange}
                >
                  <MenuItem value="Friend">Friend</MenuItem>
                  <MenuItem value="Family">Family</MenuItem>
                  <MenuItem value="Acquaintance">Acquaintance</MenuItem>
                  <MenuItem value="Other">Other</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            {formData.relationship === "Other" && (
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="Specify Relationship"
                  name="relationshipOther"
                  value={formData.relationshipOther}
                  onChange={handleChange}
                  required
                  variant="outlined"
                  autoComplete="off"
                />
              </Grid>
            )}

            {/* Experience */}
            <Grid item xs={12} sm={6}>
              <FormControl fullWidth required>
                <InputLabel id="experience-label">Experience</InputLabel>
                <Select
                  labelId="experience-label"
                  label="Experience"
                  name="experience"
                  value={formData.experience}
                  onChange={handleChange}
                >
                  <MenuItem value="Intern">Intern</MenuItem>
                  <MenuItem value="Fresher">Fresher</MenuItem>
                  <MenuItem value="Experienced">Experienced</MenuItem>
                  <MenuItem value="Other">Other</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            {formData.experience === "Other" && (
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="Specify Experience"
                  name="experienceOther"
                  value={formData.experienceOther}
                  onChange={handleChange}
                  required
                  variant="outlined"
                  autoComplete="off"
                />
              </Grid>
            )}

            {/* Referred By Section */}
            <Grid item xs={12}>
              <Typography variant="h6" fontWeight={600} mt={3} mb={1}>
                Referred By
              </Typography>
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="Referrer Name"
                name="referredBy.name"
                value={formData.referredBy.name}
                onChange={handleChange}
                required
                variant="outlined"
                autoComplete="off"
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="Referrer Email"
                name="referredBy.email"
                type="email"
                value={formData.referredBy.email}
                onChange={handleChange}
                required
                variant="outlined"
                autoComplete="off"
              />
            </Grid>

            {/* File Upload */}
            <Grid item xs={12}>
              <Stack direction="row" alignItems="center" spacing={2}>
                <Button
                  variant="contained"
                  component="label"
                  sx={{ mt: 1 }}
                  disabled={submitting}
                >
                  Upload Resume (Optional)
                  <input
                    hidden
                    type="file"
                    accept=".pdf,.doc,.docx"
                    onChange={handleFileChange}
                  />
                </Button>
                {formData.resume && (
                  <Typography variant="body2" sx={{ fontStyle: "italic" }}>
                    {formData.resume.name}
                  </Typography>
                )}
              </Stack>
            </Grid>

            {/* Submit Button */}
            <Grid item xs={12}>
              <Button
                type="submit"
                variant="contained"
                color="primary"
                fullWidth
                disabled={submitting}
                sx={{ py: 1.8, fontWeight: 600, fontSize: "1.1rem" }}
              >
                {submitting ? "Submitting..." : "Submit Referral"}
              </Button>
            </Grid>
          </Grid>
        </form>
      </Paper>
    </Box>
  );
};

export default ReferralForm;   in this whAT I WANT IS THAT the form will look like -- CANDIDATE NAME -- then texr box area ....and then in next line Candidate email -- then txt box and so on mark the fileds columniwse