/* eslint-disable -- temporary disable for development/testing purposes */

'use client';

import {
  Box,
  Button,
  Grid,
  
  TextField,
  Typography,
  Avatar,
  CircularProgress,
  IconButton, // Import IconButton
  InputAdornment, // Import InputAdornment
  MenuItem, Select, InputLabel, FormControl ,
  Divider
} from '@mui/material';
import { useEffect, useState, useContext } from 'react';
import { UserContext } from '@/contexts/user-context';
import { useRouter } from 'next/navigation';
import { Snackbar, Alert } from '@mui/material';
import { Visibility, VisibilityOff } from '@mui/icons-material'; // Import eye icons
import { SelectChangeEvent } from '@mui/material/Select';
import { ArrowBackIosNew as ArrowBackIosNewIcon } from '@mui/icons-material';

interface FormData {
  f_name: string | null;
  l_name: string | null;
  email: string | null;
  mobile_number: string | null;
  password: string | null;
  gender: string | null;
  // dob: string | null;
  address: string | null;
  // age: string | null;
  referral_source: string | null;
  z_code: string | null;
  company_id: string | null;
  lat: string | null;
  lng: string | null;
  license_number: string | null;
  npi: string | null;
  discipline: string | null;
  experience: string | null;
  weekly_capacity: string | null;
  speciality: string | null;

}

const AddPatient = () => {
  const [formData, setFormData] = useState<FormData>({
    f_name: '',
    l_name: '',
    email: '',
    mobile_number: '',
    password: '',
    gender: '',
    // dob: '',
    address: '',
    // age: '',
    referral_source: '',
    z_code: '',
    company_id: '',
    lat: '',
    lng: '',
    license_number: '',
    npi: '',
    discipline: '',
    experience: '',
    weekly_capacity: '',
    speciality:''
  });

  const [profile, setProfile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const { user: loggedInUser } = useContext(UserContext) ?? {};
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');
  const [showPassword, setShowPassword] = useState(false); // State for password visibility
  const router = useRouter();
  useEffect(() => {
    if (!loggedInUser) return;

    if (loggedInUser.role === 'manager' && loggedInUser.companies?.length > 0) {
      const activeCompany = loggedInUser.companies.find((company) => company.active);
      if (activeCompany) {
        setFormData((prev) => ({
          ...prev,
          company_id: activeCompany.id?.toString() ?? null,
        }));
      }
    }
  }, [loggedInUser]);

  useEffect(() => {
    if (!window.google) return;

    const input = document.getElementById('address-autocomplete') as HTMLInputElement;
    if (!input) return;

    const autocomplete = new window.google.maps.places.Autocomplete(input, {
      types: ['geocode'],
    });

    const placesService = new window.google.maps.places.PlacesService(input);

    autocomplete.addListener('place_changed', () => {
      const place = autocomplete.getPlace();

      const geometry = place?.geometry;
      const location = geometry?.location;

      if (location) {
        setFormData((prev) => ({
          ...prev,
          address: place.formatted_address || prev.address,
          lat: location.lat().toString(),
          lng: location.lng().toString(),
        }));
      } else {
        console.log("No valid geometry and location found for the selected place.");
        setFormData(prev => ({ ...prev, lat: '', lng: '' }));
      }
    });

    return () => {
      if (autocomplete) {
        window.google.maps.event.clearInstanceListeners(autocomplete);
      }
    };
  }, []);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | SelectChangeEvent
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  
    if (name === 'dob') {
      calculateAge(value);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setProfile(e.target.files[0]);
    }
  };

  const handleSubmit = async () => {
    console.log('Form Data before validation and submission:', formData);

    if (!formData.f_name?.trim()) {
      console.error('Validation Error: First Name is required.');
      return;
    }
    if (!formData.l_name?.trim()) {
      console.error('Validation Error: Last Name is required.');
      return;
    }
    if (!formData.email?.trim()) {
      console.error('Validation Error: Email is required.');
      return;
    } else if (formData.email && !/\S+@\S+\.\S+/.test(formData.email)) {
      console.error('Validation Error: Invalid email format.');
      return;
    }
    if (!formData.mobile_number?.trim()) {
      console.error('Validation Error: Mobile Number is required.');
      return;
    }

    const data = new FormData();
    const fullName = `${formData.f_name} ${formData.l_name}`.trim();
    data.append('name', fullName);

    const dataToSend: typeof formData = { ...formData };

    for (const key in dataToSend) {
      if (dataToSend[key as keyof typeof formData] === '') {
        dataToSend[key as keyof typeof formData] = null;
      }
    }

    for (const key in dataToSend) {
      if (key !== 'f_name' && key !== 'l_name') {
        data.append(
          key,
          dataToSend[key as keyof typeof formData] === null
            ? ''
            : dataToSend[key as keyof typeof formData]!
        );
      }
    }

    if (profile) {
      data.append('profile', profile);
    }

    setLoading(true);

    try {
      const response = await fetch('/admin/api/provider/add', {
        method: 'POST',
        body: data,
      });

      let responseData;
      try {
        responseData = await response.json();
      } catch (err) {
        console.error('Failed to parse JSON:', err);
      }

      if (!response.ok) {
        console.error('Server Error:', responseData?.error || 'Unknown error');
      } else {
        console.log('Patient added:', responseData.message);
        setFormData({
          f_name: null,
          l_name: null,
          email: null,
          mobile_number: null,
          password: null,
          gender: null,
          // dob: null,
          address: null,
          // age: null,
          referral_source: null,
          z_code: null,
          company_id:
            loggedInUser?.role === 'manager'
              ? loggedInUser.companies?.find((c) => c.active)?.id?.toString() ?? null
              : null,
          lat: null,
          lng: null,
          license_number: null,
          npi: null,
          discipline: null,
          experience: null,
          weekly_capacity: null,
          speciality:null
        
         
        });
        setProfile(null);
        setSnackbarMessage('Provider added successfully');
await sendWelcomeEmail(fullName, formData.email || '', formData.password || '');
        
        setSnackbarSeverity('success');
        setSnackbarOpen(true);
  
        // Redirect to /customers after a delay
        setTimeout(() => {
          router.push('/dashboard/providers');
        }, 2000);
      }
    } catch (err) {
      console.error('Unexpected error:', err);
    } finally {
      setLoading(false);
    }
  };
  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  const handleMouseDownPassword = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
  };

  const calculateAge = (dob: string | null) => {
    if (dob) {
      const birthDate = new Date(dob);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      setFormData((prev) => ({ ...prev, age: age.toString() }));
    } else {
      setFormData((prev) => ({ ...prev, age: '' }));
    }
  };

  const sendWelcomeEmail = async (name: string, email: string, password: string) => {
    if (!loggedInUser?.name) {
      console.error('Manager name not available, cannot send welcome email.');
      return;
    }
  
    const emailData = new FormData();
    emailData.append('name', name);
    emailData.append('receiver_email', email);
    emailData.append('user_type', 'provider');
    emailData.append('password', password);
    emailData.append('manager_name', loggedInUser.name);
    emailData.append('action', 'send_new_user_notification');
  
    try {
      const response = await fetch('https://gohelloprovider.com/api/emailproject/send_email.php', {
        method: 'POST',
        body: emailData,
      });
  
      const data = await response.json();
      console.log('Email API response:', data);
  
      if (data.response === 'success') {
        // setSnackbarMessage('Welcome email sent successfully');
        // setSnackbarSeverity('success');
      } else {
        // setSnackbarMessage('Failed to send welcome email');
        // setSnackbarSeverity('error');
      }
      // setSnackbarOpen(true);
    } catch (error) {
      console.error('Error sending welcome email:', error);
      // setSnackbarMessage('Error sending welcome email');
      // setSnackbarSeverity('error');
      // setSnackbarOpen(true);
    }
  };
 

  return (
    <>
    <Box sx={{ maxWidth: 600, mx: 'auto', mt: 4, p: 3, bgcolor: '#fff', borderRadius: 2 }}>
 
  <Box display="flex" alignItems="center" mb={2}>
  <IconButton onClick={() => window.history.back()} sx={{ mr: 1 }}>
    <ArrowBackIosNewIcon /> {/* or <ArrowBackIcon /> */}
  </IconButton>
  <Typography variant="h5">Add New Provider</Typography>
</Box>

  <Grid container spacing={2}>
    {/* PROFILE IMAGE UPLOAD */}
    <Grid item xs={12} textAlign="center">
      <Avatar
        alt="Profile"
        src={profile ? URL.createObjectURL(profile) : ''}
        sx={{ width: 100, height: 100, margin: '0 auto', mb: 1 }}
      />
      <Button variant="outlined" component="label">
        {profile ? 'Change Profile' : 'Upload Profile'}
        <input hidden type="file" accept="image/*" onChange={handleFileChange} />
      </Button>
    </Grid>

    {/* SECTION: PERSONAL DETAILS */}
    <Grid item xs={12}>
      <Typography variant="h6" gutterBottom>Personal Details</Typography>
      <Divider />
    </Grid>

    <Grid item xs={6}>
      <TextField label="First Name" name="f_name" value={formData.f_name || ''} onChange={handleChange} fullWidth />
    </Grid>

    <Grid item xs={6}>
      <TextField label="Last Name" name="l_name" value={formData.l_name || ''} onChange={handleChange} fullWidth />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="Email"
        name="email"
        autoComplete="off"
        type="email"
        value={formData.email || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        autoComplete="off"
        type="tel"
        label="Mobile Number"
        name="mobile_number"
        value={formData.mobile_number || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        autoComplete="new-password"
        label="Password"
        name="password"
        type={showPassword ? 'text' : 'password'} 
        value={formData.password || ''}
        onChange={handleChange}
        fullWidth
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton
                aria-label="toggle password visibility"
                onClick={handleClickShowPassword}
                onMouseDown={handleMouseDownPassword}
                edge="end"
              >
                {showPassword ? <VisibilityOff /> : <Visibility />}
              </IconButton>
            </InputAdornment>
          ),
        }}
      />
    </Grid>

    {/* <Grid item xs={6}>
      <TextField label="Age" name="age" type="number" value={formData.age || ''} onChange={handleChange} fullWidth />
    </Grid> */}

    <Grid item xs={6}>
      <TextField label="Gender" name="gender" select value={formData.gender || ''} onChange={handleChange} fullWidth>
        <MenuItem value="">Select Gender</MenuItem>
        <MenuItem value="male">Male</MenuItem>
        <MenuItem value="female">Female</MenuItem>
        <MenuItem value="other">Other</MenuItem>
      </TextField>
    </Grid>

    {/* <Grid item xs={6}>
      <TextField
        label="Date of Birth"
        name="dob"
        type="date"
        value={formData.dob || ''}
        onChange={handleChange}
        InputLabelProps={{ shrink: true }}
        fullWidth
      />
    </Grid> */}

    <Grid item xs={12}>
      <TextField
        id="address-autocomplete"
        label="Address"
        name="address"
        value={formData.address || ''}
        onChange={handleChange}
        fullWidth
        multiline
        rows={2}
      />
    </Grid>

    {/* SECTION: OTHER DETAILS */}
    <Grid item xs={12} mt={2}>
      <Typography variant="h6" gutterBottom>Other Details</Typography>
      <Divider />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="Referral Source"
        name="referral_source"
        value={formData.referral_source || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="Zip Code"
        name="z_code"
        value={formData.z_code || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="License Number"
        name="license_number"
        value={formData.license_number || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="NPI"
        name="npi"
        value={formData.npi || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="Discipline"
        name="discipline"
        value={formData.discipline || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="Experience (Years)"
        name="experience"
        type="number"
        value={formData.experience || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <TextField
        label="Weekly Capacity (Hours)"
        name="weekly_capacity"
        type="number"
        value={formData.weekly_capacity || ''}
        onChange={handleChange}
        fullWidth
      />
    </Grid>

    <Grid item xs={6}>
      <FormControl fullWidth>
        <InputLabel>Speciality</InputLabel>
        <Select
          label="Speciality"
          name="speciality"
          value={formData.speciality || ''}
          onChange={handleChange}
        >
          <MenuItem value="">Select Specialty</MenuItem>
          <MenuItem value="Physical Therapy">Physical Therapy</MenuItem>
          <MenuItem value="Occupational Therapy">Occupational Therapy</MenuItem>
          <MenuItem value="Speech Therapy">Speech Therapy</MenuItem>
          <MenuItem value="Massage Therapy">Massage Therapy</MenuItem>
          <MenuItem value="Mental Health">Mental Health</MenuItem>
          <MenuItem value="Social Worker">Social Worker</MenuItem>
          <MenuItem value="Dietation">Dietation</MenuItem>
          <MenuItem value="Nurse Practitioner">Nurse Practitioner</MenuItem>
        </Select>
      </FormControl>
    </Grid>

    {/* Hidden lat/lng inputs */}
    <input type="hidden" name="lat" value={formData.lat || ''} />
    <input type="hidden" name="lng" value={formData.lng || ''} />

    {/* SUBMIT BUTTON */}
    <Grid item xs={12}>
      <Button variant="contained" onClick={handleSubmit} disabled={loading} fullWidth>
        {loading ? <CircularProgress size={22} /> : 'Add Provider'}
      </Button>
    </Grid>
  </Grid>

  {/* SNACKBAR */}
  <Snackbar
    open={snackbarOpen}
    autoHideDuration={4000}
    onClose={() => setSnackbarOpen(false)}
    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
  >
    <Alert
      onClose={() => setSnackbarOpen(false)}
      severity={snackbarSeverity}
      variant="filled"
      sx={{ width: '100%' }}
    >
      {snackbarMessage}
    </Alert>
  </Snackbar>
</Box>

  </>
  );
};

export default AddPatient;
