import React, { useState, useEffect } from "react";
import {
  Box,
  TextField,
  Button,
  Typography,
  Paper,
  Stack,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Dialog,
  DialogContent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  CircularProgress,
  Divider
} from "@mui/material";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import CancelIcon from "@mui/icons-material/Cancel";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
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 [openDialog, setOpenDialog] = useState(false);
  
  // New states for fetching and displaying referrals
  const [referrals, setReferrals] = useState([]);
  const [loading, setLoading] = useState(false);
  const [fetchError, setFetchError] = useState("");
  const [expanded, setExpanded] = useState(false);

  // Fetch all referrals on component mount and after successful submission
  useEffect(() => {
    fetchReferrals();
  }, []);

  // Function to fetch all referrals
  const fetchReferrals = async () => {
    setLoading(true);
    setFetchError("");
    try {
      const response = await axios.get("http://localhost:5000/api/referral/all");
      setReferrals(response.data);
    } catch (error) {
      console.error("Error fetching referrals:", error);
      setFetchError(
        error.response?.data?.message || "Failed to fetch referrals. Please try again."
      );
    } finally {
      setLoading(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 handleCloseDialog = () => {
    setOpenDialog(false);
    // Only reset the form if submission was successful
    if (message.type === "success") {
      setFormData({
        candidateName: "",
        email: "",
        mobile: "",
        experience: "",
        experienceOther: "",
        applyingFor: "",
        applyingForOther: "",
        relationship: "",
        relationshipOther: "",
        referredBy: {
          name: "",
          email: "",
        },
        resume: null,
      });
      // Refresh referrals after successful submission
      fetchReferrals();
    }
  };

  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.",
          subtext: "Try again with complete information."
        });
        setOpenDialog(true);
        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: "Thank You!",
        subtext: "Your details have been successfully submitted. Thanks!"
      });
      setOpenDialog(true);
    } catch (error) {
      console.error("Error submitting referral:", error);
      const errorMsg =
        error.response?.data?.message ||
        "Error submitting referral. Please try again.";
      setMessage({ 
        type: "error", 
        text: "Submission Failed",
        subtext: errorMsg
      });
      setOpenDialog(true);
    } finally {
      setSubmitting(false);
    }
  };

  // Format date for display
  const formatDate = (dateString) => {
    const options = { 
      year: 'numeric', 
      month: 'short', 
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    };
    return new Date(dateString).toLocaleDateString(undefined, options);
  };

  return (
    <Box
      sx={{
        maxWidth: 920,
        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>

        <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>

      {/* Referrals List Section */}
      <Paper elevation={4} sx={{ p: { xs: 3, sm: 5 }, mt: 4 }}>
        <Accordion 
          expanded={expanded} 
          onChange={() => setExpanded(!expanded)}
          sx={{ boxShadow: 'none' }}
        >
          <AccordionSummary 
            expandIcon={<ExpandMoreIcon />}
            sx={{ px: 0 }}
          >
            <Typography variant="h5" fontWeight={600}>
              View All Referrals
            </Typography>
          </AccordionSummary>
          <AccordionDetails sx={{ px: 0 }}>
            <Box sx={{ mb: 2 }}>
              <Button 
                variant="outlined" 
                onClick={fetchReferrals}
                startIcon={loading && <CircularProgress size={20} />}
                disabled={loading}
              >
                {loading ? "Loading..." : "Refresh Referrals"}
              </Button>
            </Box>

            {fetchError && (
              <Typography color="error" sx={{ mb: 2 }}>
                {fetchError}
              </Typography>
            )}

            {referrals.length > 0 ? (
              <TableContainer component={Paper} sx={{ maxHeight: 440, boxShadow: 'none' }}>
                <Table stickyHeader aria-label="referrals table">
                  <TableHead>
                    <TableRow>
                      <TableCell sx={{ fontWeight: 'bold' }}>Candidate Name</TableCell>
                      <TableCell sx={{ fontWeight: 'bold' }}>Position</TableCell>
                      <TableCell sx={{ fontWeight: 'bold' }}>Experience</TableCell>
                      <TableCell sx={{ fontWeight: 'bold' }}>Referred By</TableCell>
                      <TableCell sx={{ fontWeight: 'bold' }}>Date Submitted</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {referrals.map((referral) => (
                      <TableRow key={referral._id} hover>
                        <TableCell component="th" scope="row">
                          <Typography variant="body2" fontWeight={500}>
                            {referral.candidateName}
                          </Typography>
                          <Typography variant="caption" color="textSecondary">
                            {referral.email}
                          </Typography>
                        </TableCell>
                        <TableCell>{referral.applyingFor}</TableCell>
                        <TableCell>{referral.experience}</TableCell>
                        <TableCell>
                          <Typography variant="body2">
                            {referral.referredBy.name}
                          </Typography>
                          <Typography variant="caption" color="textSecondary">
                            {referral.referredBy.email}
                          </Typography>
                        </TableCell>
                        <TableCell>
                          {referral.createdAt && formatDate(referral.createdAt)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            ) : (
              <Typography variant="body1" sx={{ py: 3, textAlign: 'center' }}>
                {loading ? "Loading referrals..." : "No referrals found"}
              </Typography>
            )}
          </AccordionDetails>
        </Accordion>
      </Paper>

      {/* Styled Popup Dialog for messages */}
      <Dialog
        open={openDialog}
        onClose={handleCloseDialog}
        PaperProps={{
          sx: {
            maxWidth: "350px",
            width: "100%",
            borderRadius: "8px",
            boxShadow: "0 4px 20px rgba(0,0,0,0.15)",
          }
        }}
      >
        <Box sx={{ 
          position: "relative",
          textAlign: "center",
          pt: 0
        }}>
          {/* Dark blue header banner */}
          <Box sx={{ 
            bgcolor: "#3c5279",
            height: "80px",
            width: "100%",
            position: "absolute",
            top: 0,
            zIndex: 0
          }} />

          {/* Icon Circle */}
          <Box sx={{ 
            mx: "auto",
            width: "70px",
            height: "70px",
            borderRadius: "50%",
            bgcolor: message.type === "success" ? "#5cd65c" : "#ff5252",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            position: "relative",
            top: "45px",
            zIndex: 1
          }}>
            {message.type === "success" ? (
              <CheckCircleIcon sx={{ fontSize: "40px", color: "white" }} />
            ) : (
              <CancelIcon sx={{ fontSize: "40px", color: "white" }} />
            )}
          </Box>
        </Box>

        <DialogContent sx={{ mt: 6, pt: 4, px: 3, pb: 3 }}>
          <Typography variant="h6" fontWeight="bold" sx={{ mb: 1, textAlign: "center" }}>
            {message.text}
          </Typography>
          <Typography variant="body2" sx={{ mb: 3, textAlign: "center" }}>
            {message.subtext}
          </Typography>
          <Button
            fullWidth
            variant="contained"
            onClick={handleCloseDialog}
            sx={{
              bgcolor: message.type === "success" ? "#5cd65c" : "#ff5252",
              color: "white",
              py: 1,
              "&:hover": {
                bgcolor: message.type === "success" ? "#4caf50" : "#d32f2f",
              }
            }}
          >
            OK
          </Button>
        </DialogContent>
      </Dialog>
    </Box>
  );
};

export default ReferralForm;    in this i wanted the resmue not to be optional ...its mandtory field also on the api i wanted the pdf or word of the resume ...also after applying for a text box for position ...and which is also mandatory ...mobile number .....optional