import React, { useState } from "react";
import {
  Box,
  TextField,
  Button,
  Typography,
  Paper,
  Alert,
  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 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 required fields (including 'Other' fields)
      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>
          <Stack spacing={3}>
            {/* Candidate Name */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Candidate Name
              </Typography>
              <TextField
                fullWidth
                name="candidateName"
                value={formData.candidateName}
                onChange={handleChange}
                required
                autoComplete="off"
                variant="outlined"
              />
            </Box>

            {/* Candidate Email */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Candidate Email
              </Typography>
              <TextField
                fullWidth
                name="email"
                type="email"
                value={formData.email}
                onChange={handleChange}
                required
                autoComplete="off"
                variant="outlined"
              />
            </Box>

            {/* Mobile Number */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Mobile Number
              </Typography>
              <TextField
                fullWidth
                name="mobile"
                value={formData.mobile}
                onChange={handleChange}
                required
                variant="outlined"
                inputProps={{ maxLength: 15 }}
                autoComplete="off"
              />
            </Box>

            {/* Applying For */}
            <Box>
              <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>
            </Box>
            {formData.applyingFor === "Other" && (
              <Box>
                <Typography variant="subtitle1" gutterBottom>
                  Specify Applying For
                </Typography>
                <TextField
                  fullWidth
                  name="applyingForOther"
                  value={formData.applyingForOther}
                  onChange={handleChange}
                  required
                  variant="outlined"
                  autoComplete="off"
                />
              </Box>
            )}

            {/* Relationship */}
            <Box>
              <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>
            </Box>
            {formData.relationship === "Other" && (
              <Box>
                <Typography variant="subtitle1" gutterBottom>
                  Specify Relationship
                </Typography>
                <TextField
                  fullWidth
                  name="relationshipOther"
                  value={formData.relationshipOther}
                  onChange={handleChange}
                  required
                  variant="outlined"
                  autoComplete="off"
                />
              </Box>
            )}

            {/* Experience */}
            <Box>
              <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>
            </Box>
            {formData.experience === "Other" && (
              <Box>
                <Typography variant="subtitle1" gutterBottom>
                  Specify Experience
                </Typography>
                <TextField
                  fullWidth
                  name="experienceOther"
                  value={formData.experienceOther}
                  onChange={handleChange}
                  required
                  variant="outlined"
                  autoComplete="off"
                />
              </Box>
            )}

            {/* Referred By Section */}
            <Box>
              <Typography variant="h6" fontWeight={600} mt={3} mb={1}>
                Referred By
              </Typography>
            </Box>

            {/* Referrer Name */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Referrer Name
              </Typography>
              <TextField
                fullWidth
                name="referredBy.name"
                value={formData.referredBy.name}
                onChange={handleChange}
                required
                variant="outlined"
                autoComplete="off"
              />
            </Box>

            {/* Referrer Email */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Referrer Email
              </Typography>
              <TextField
                fullWidth
                name="referredBy.email"
                type="email"
                value={formData.referredBy.email}
                onChange={handleChange}
                required
                variant="outlined"
                autoComplete="off"
              />
            </Box>

            {/* File Upload */}
            <Box>
              <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>
            </Box>

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

export default ReferralForm;   what if we want to add someone in CC also