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,
  Alert,
  Autocomplete,
  Chip,
} 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 SearchIcon from "@mui/icons-material/Search";
import PersonIcon from "@mui/icons-material/Person";
import axios from "axios";

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

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

  // States for referrers from backend
  const [referrers, setReferrers] = useState([]);
  const [referrersLoading, setReferrersLoading] = useState(true);
  const [referrersError, setReferrersError] = useState("");

  // 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 referrers from backend on component mount
  useEffect(() => {
    fetchReferrers();
    fetchReferrals();
  }, []);

  // Function to fetch referrers from backend
  const fetchReferrers = async () => {
    setReferrersLoading(true);
    setReferrersError("");
    try {
      const response = await axios.get("http://192.168.10.31:5000/api/referrers");
      
      // Sort referrers alphabetically by name
      const sortedReferrers = response.data
        .map(referrer => ({
          ...referrer,
          displayName: ${referrer.name} - ${referrer.designation || 'No designation'} (${referrer.department || 'No department'})
        }))
        .sort((a, b) => a.name.localeCompare(b.name));
      
      setReferrers(sortedReferrers);
    } catch (error) {
      console.error("Error fetching referrers:", error);
      setReferrersError(
        error.response?.data?.message || "Failed to load referrers. Please refresh the page."
      );
    } finally {
      setReferrersLoading(false);
    }
  };

  // Function to fetch all referrals
  const fetchReferrals = async () => {
    setLoading(true);
    setFetchError("");
    try {
      const response = await axios.get("http://192.168.10.31: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,
      }));
    }
  };

  // Handle referrer selection from Autocomplete
  const handleReferrerChange = (event, newValue) => {
    if (newValue) {
      setFormData((prev) => ({
        ...prev,
        referredBy: {
          name: newValue.name,
          email: newValue.email,
          designation: newValue.designation,
          department: newValue.department,
        },
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        referredBy: {
          name: "",
          email: "",
          designation: "",
          department: "",
        },
      }));
    }
  };

  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: "",
        position: "",
        relationship: "",
        relationshipOther: "",
        referredBy: {
          name: "",
          email: "",
          designation: "",
        },
        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;

      // Resume - mandatory and validate file type
      if (!formData.resume) {
        setMessage({
          type: "error",
          text: "Resume Required",
          subtext: "Please upload your resume in PDF or Word format.",
        });
        setOpenDialog(true);
        setSubmitting(false);
        return;
      } else {
        const allowedTypes = [
          "application/pdf",
          "application/msword",
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ];
        if (!allowedTypes.includes(formData.resume.type)) {
          setMessage({
            type: "error",
            text: "Invalid File Type",
            subtext: "Upload PDF or Word document (.pdf, .doc, .docx) only.",
          });
          setOpenDialog(true);
          setSubmitting(false);
          return;
        }
      }

      // Validate required fields
      if (
        !formData.candidateName.trim() ||
        !formData.email.trim() ||
        !applyingForToSend ||
        !formData.position.trim() ||  // Position mandatory
        !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()); // optional, may be empty string
      formDataToSend.append("applyingFor", applyingForToSend);
      formDataToSend.append("position", formData.position.trim()); // position appended
      formDataToSend.append("relationship", relationshipToSend);
      formDataToSend.append("experience", experienceToSend);
      
      // Include referrer details with designation for email formatting
      const referrerInfo = {
        ...formData.referredBy,
        emailMessage: We've received a referral from Mr./Ms. ${formData.referredBy.name} (${formData.referredBy.designation}) for the **${formData.position}**. The candidate's details are attached for your review and assessment.
      };
      formDataToSend.append("referredBy", JSON.stringify(referrerInfo));

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

      await axios.post(
        "http://192.168.10.31: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>

        {/* Referrers Loading State */}
        {referrersLoading && (
          <Box sx={{ mb: 4 }}>
            <Alert severity="info" icon={<CircularProgress size={20} />}>
              Loading employee data...
            </Alert>
          </Box>
        )}

        {/* Referrers Error State */}
        {referrersError && (
          <Box sx={{ mb: 4 }}>
            <Alert 
              severity="error" 
              action={
                <Button color="inherit" size="small" onClick={fetchReferrers}>
                  Retry
                </Button>
              }
            >
              {referrersError}
            </Alert>
          </Box>
        )}

        <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 - OPTIONAL */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Mobile Number (Optional)
              </Typography>
              <TextField
                fullWidth
                name="mobile"
                value={formData.mobile}
                onChange={handleChange}
                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="Colleague">Colleague</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="1-3 years">1-3 years</MenuItem>
                  <MenuItem value="3-5 years">3-5 years</MenuItem>
                  <MenuItem value="5+ years">5+ years</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>
            )}

            {/* Position - New mandatory field */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Position
              </Typography>
              <TextField
                fullWidth
                name="position"
                value={formData.position}
                onChange={handleChange}
                required
                variant="outlined"
                autoComplete="off"
                placeholder="Ex- Associate, Senior Associate, etc."
              />
            </Box>

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

            {/* Searchable Referrer Autocomplete */}
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                Select Referrer <span style={{ color: 'red' }}>*</span>
              </Typography>
              <Autocomplete
                options={referrers}
                getOptionLabel={(option) => option.displayName}
                value={referrers.find(r => r.email === formData.referredBy.email) || null}
                onChange={handleReferrerChange}
                disabled={referrersLoading || referrersError}
                loading={referrersLoading}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    placeholder="Search employee by name, designation, or department..."
                    variant="outlined"
                    required
                    InputProps={{
                      ...params.InputProps,
                      startAdornment: <SearchIcon sx={{ mr: 1, color: 'text.secondary' }} />,
                      endAdornment: (
                        <>
                          {referrersLoading ? <CircularProgress color="inherit" size={20} /> : null}
                          {params.InputProps.endAdornment}
                        </>
                      ),
                    }}
                  />
                )}
                renderOption={(props, option) => (
                  <Box component="li" {...props}>
                    <PersonIcon sx={{ mr: 2, color: 'primary.main' }} />
                    <Box>
                      <Typography variant="body2" fontWeight={600}>
                        {option.name}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {option.designation} • {option.department || 'No department'}
                      </Typography>
                    </Box>
                  </Box>
                )}
                filterOptions={(options, { inputValue }) => {
                  const filtered = options.filter(option =>
                    option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
                    option.designation.toLowerCase().includes(inputValue.toLowerCase()) ||
                    (option.department && option.department.toLowerCase().includes(inputValue.toLowerCase()))
                  );
                  return filtered;
                }}
                noOptionsText={
                  referrersLoading ? "Loading employees..." : 
                  referrersError ? "Error loading employees" : 
                  "No employees found"
                }
              />
              <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                {referrers.length > 0 && ${referrers.length} employees available}
              </Typography>
            </Box>

            {/* Display selected referrer details */}
            {formData.referredBy.name && (
              <Box sx={{ p: 2, bgcolor: 'grey.50', borderRadius: 1, border: '1px solid', borderColor: 'grey.300' }}>
                <Typography variant="subtitle2" gutterBottom color="primary">
                  Selected Referrer Details:
                </Typography>
                <Stack direction="row" spacing={1} sx={{ mb: 1, flexWrap: 'wrap' }}>
                  <Chip 
                    label={Name: ${formData.referredBy.name}} 
                    variant="outlined" 
                    size="small"
                    icon={<PersonIcon />}
                  />
                  {formData.referredBy.designation && (
                    <Chip 
                      label={Designation: ${formData.referredBy.designation}} 
                      variant="outlined" 
                      size="small"
                    />
                  )}
                  {formData.referredBy.department && (
                    <Chip 
                      label={Department: ${formData.referredBy.department}} 
                      variant="outlined" 
                      size="small"
                    />
                  )}
                </Stack>
                <Typography variant="body2">
                  <strong>Email:</strong> {formData.referredBy.email}
                </Typography>
                <Typography variant="body2" sx={{ mt: 1, fontStyle: 'italic', p: 2, bgcolor: 'info.light', borderRadius: 1 }}>
                  <strong>Email Message Preview:</strong><br />
                  We've received a referral from Mr./Ms. {formData.referredBy.name} ({formData.referredBy.designation}) for the <strong>{formData.position || '[Position Name]'}</strong>. The candidate's details are attached for your review and assessment.
                </Typography>
              </Box>
            )}

            {/* File Upload - Mandatory */}
            <Box>
              <Stack direction="row" alignItems="center" spacing={2}>
                <Button
                  variant="contained"
                  component="label"
                  sx={{ mt: 1 }}
                  disabled={submitting}
                >
                  Upload Resume (PDF or Word, Required)
                  <input
                    hidden
                    type="file"
                    name="resume" 
                    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 || referrersLoading || referrersError}
                sx={{ py: 1.8, fontWeight: 600, fontSize: "1.1rem" }}
              >
                {submitting ? "Submitting...Please Wait a Moment" : "Submit Referral"}
              </Button>
            </Box>
          </Stack>
        </form>
      </Paper>

      {/* Referrals Display Section */}
      <Box sx={{ mt: 4 }}>
        <Accordion expanded={expanded} onChange={() => setExpanded(!expanded)}>
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="h6" fontWeight={600}>
              View All Referrals ({referrals.length})
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            {loading && (
              <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
                <CircularProgress />
              </Box>
            )}
            
            {fetchError && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {fetchError}
              </Alert>
            )}
            
            {!loading && !fetchError && referrals.length === 0 && (
              <Typography variant="body2" color="text.secondary" align="center">
                No referrals found.
              </Typography>
            )}
            
            {!loading && referrals.length > 0 && (
              <TableContainer component={Paper} variant="outlined">
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell><strong>Candidate</strong></TableCell>
                      <TableCell><strong>Email</strong></TableCell>
                      <TableCell><strong>Position</strong></TableCell>
                      <TableCell><strong>Referred By</strong></TableCell>
                      <TableCell><strong>Date</strong></TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {referrals.map((referral, index) => (
                      <TableRow key={index}>
                        <TableCell>{referral.candidateName}</TableCell>
                        <TableCell>{referral.email}</TableCell>
                        <TableCell>{referral.position}</TableCell>
                        <TableCell>{referral.referredBy?.name}</TableCell>
                        <TableCell>{formatDate(referral.submittedAt)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </AccordionDetails>
        </Accordion>
      </Box>

      {/* 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;     ye code h hume prodution m move krna h to refeer k details fix h but koi new employee aaega to join b krega usko b add krte jana h also abhi hum 175 employee ko baith k ik ik add ni kr skte ..they are in excel now ...so tell me approach for prod and lso code