import React, { useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Button,
  Grid,
  TextField,
  Box,
  Alert,
  IconButton,
  Chip,
  Avatar,
  Autocomplete,
  CircularProgress,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';

import AddPhotoAlternateIcon from '@mui/icons-material/AddPhotoAlternate';
import MapComponent from 'components/base/MapComponent';
import { AttorneyAPI, AutocompleteDataResponseAPI } from 'types';
import { PlacePrediction } from './AddPropertyDialog';
import { test_autocomplete } from 'data/mock_autocomplete_results';
import { axiosInstance, axiosRealEstateApi } from '../../../../../axiosApi';
import { extractLatLon } from 'utils';

interface AttorneyProfileCardProps {
  attorney: AttorneyAPI;
  onUpgrade: () => void; // Assuming attorneys can also upgrade their tier
  onSave: (updatedAttorney: AttorneyAPI) => void;
}

const AttorneyProfileCard: React.FC<AttorneyProfileCardProps> = ({
  attorney,
  onUpgrade,
  onSave,
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editedAttorney, setEditedAttorney] = useState<AttorneyAPI>(attorney);
  const [formErrors, setFormErrors] = useState<{ [key: string]: string }>({});

  const [autocompleteOptions, setAutocompleteOptions] = useState<PlacePrediction[]>([]);
  const [autocompleteLoading, setAutocompleteLoading] = useState(false);

  const handleEditToggle = () => {
    if (isEditing) {
      setEditedAttorney(attorney); // Revert on cancel
      setFormErrors({});
    }
    setIsEditing(!isEditing);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setEditedAttorney((prev) => ({
      ...prev,
      [name]: value,
      // Handle nested user properties if you allow editing them here
      user:
        name === 'email' || name === 'first_name' || name === 'last_name'
          ? { ...prev.user, [name]: value }
          : prev.user,
    }));

    if (formErrors[name]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handleNumericChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const numValue = parseInt(value);
    setEditedAttorney((prev) => ({
      ...prev,
      [name]: isNaN(numValue) ? '' : numValue, // Allow empty string for numerical input
    }));
    if (formErrors[name]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handleArrayChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
    field: keyof AttorneyAPI,
  ) => {
    const value = e.target.value;
    setEditedAttorney((prev) => ({
      ...prev,
      [field]: value
        .split(',')
        .map((item) => item.trim())
        .filter((item) => item !== ''),
    }));
  };

  const handleProfilePictureUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      const imageUrl = URL.createObjectURL(file);
      setEditedAttorney((prev) => ({ ...prev, profile_picture: imageUrl }));
    }
  };

  const handleAddressAutocompleteInputChange = async (
    event: React.SyntheticEvent,
    value: string,
  ) => {
    const test: boolean = !import.meta.env.USE_LIVE_DATA;
    let data: AutocompleteDataResponseAPI[] = [];
    if (value.length > 2) {
      if (test) {
        data = test_autocomplete.data.filter((item) => item.address.includes(value));
        // filter the data here
      } else {
        const { data } = await axiosRealEstateApi.post<AutocompleteDataResponseAPI[]>(
          'AutoComplete',
          {
            search: value,
          },
        );
      }
      setAutocompleteOptions(
        data.map((item) => ({
          description: item.address,
          place_id: item.id,
        })),
      );
    } else {
      console.log('we need more characters');
    }
  };

  const handleAddressAutocompleteChange = async (
    event: React.SyntheticEvent,
    value: PlacePrediction | null,
  ) => {
    if (1) {
      const data = test_autocomplete.data.filter((item) => item.id === value.place_id);
      if (data.length > 0) {
        const item = data[0];
        const coordinates = extractLatLon(item.location);
        setEditedAttorney((prev) => ({
          ...prev,
          address: item.address,
          city: item.city,
          state: item.state,
          zip_code: item.zip,
          latitude: Number(coordinates.latitude),
          longitude: Number(coordinates.longitude),
        }));
      }
    } else {
      // use the api here
    }
  };

  console.log(editedAttorney);

  const validateForm = () => {
    const errors: { [key: string]: string } = {};
    if (!editedAttorney.firm_name.trim()) {
      errors.firm_name = 'Firm name is required.';
    }
    if (!editedAttorney.phone_number.trim()) {
      errors.phone_number = 'Phone number is required.';
    } else if (!/^\d{10}$/.test(editedAttorney.phone_number.replace(/\D/g, ''))) {
      errors.phone_number = 'Invalid phone number format (10 digits).';
    }
    if (!editedAttorney.address.trim()) {
      errors.address = 'Address is required.';
    }
    if (!editedAttorney.city.trim()) {
      errors.city = 'City is required.';
    }
    if (!editedAttorney.state.trim()) {
      errors.state = 'State is required.';
    }
    if (!editedAttorney.zip_code.trim()) {
      errors.zip_code = 'Zip code is required.';
    }
    if (editedAttorney.years_experience < 0) {
      errors.years_experience = 'Years of experience cannot be negative.';
    }
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSave = () => {
    if (validateForm()) {
      onSave(editedAttorney);
      setIsEditing(false);
    }
  };

  const displayLat = editedAttorney.latitude ?? 34.0522; // Default to LA for demo
  const displayLng = editedAttorney.longitude ?? -118.2437; // Default to LA for demo

  return (
    <Card sx={{ mt: 3, p: 2 }}>
      <CardContent>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Box display="flex" alignItems="center" gap={2}>
            <Avatar
              src={
                editedAttorney.profile_picture ||
                'https://via.placeholder.com/150/808080/FFFFFF?text=ATTY'
              }
              alt={`${editedAttorney.user.first_name} ${editedAttorney.user.last_name}`}
              sx={{ width: 80, height: 80 }}
            />
            <Box>
              <Typography variant="h5" gutterBottom>
                Attorney Profile Information
              </Typography>
              <Typography variant="subtitle1" color="text.secondary">
                {editedAttorney.firm_name}
              </Typography>
            </Box>
          </Box>
          {isEditing ? (
            <Box>
              <IconButton color="primary" onClick={handleSave}>
                <SaveIcon />
              </IconButton>
              <IconButton color="secondary" onClick={handleEditToggle}>
                <CancelIcon />
              </IconButton>
            </Box>
          ) : (
            <IconButton color="primary" onClick={handleEditToggle}>
              <EditIcon />
            </IconButton>
          )}
        </Box>
        <Grid container spacing={2} sx={{ mt: 2 }}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="First Name"
              name="first_name"
              value={editedAttorney.user.first_name}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Last Name"
              name="last_name"
              value={editedAttorney.user.last_name}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12, md: 6 }}>
            <TextField
              fullWidth
              label="Email Address"
              name="email"
              type="email"
              value={editedAttorney.user.email}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12, md: 6 }}>
            <TextField
              fullWidth
              label="Firm Name"
              name="firm_name"
              value={editedAttorney.firm_name}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.firm_name}
              helperText={formErrors.firm_name}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Phone Number"
              name="phone_number"
              value={editedAttorney.phone_number}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.phone_number}
              helperText={formErrors.phone_number}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <Autocomplete
              options={autocompleteOptions}
              getOptionLabel={(option) => option.description}
              inputValue={editedAttorney.adress}
              noOptionsText={'Type at least 3 characters'}
              onInputChange={handleAddressAutocompleteInputChange}
              onChange={handleAddressAutocompleteChange}
              isOptionEqualToValue={(option, value) => option.place_id === value.place_id}
              loading={autocompleteLoading}
              renderInput={(params) => (
                <TextField
                  {...params}
                  fullWidth
                  label="Address"
                  name="address"
                  required
                  error={!!formErrors.address}
                  helperText={formErrors.address}
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <>
                        {autocompleteLoading ? (
                          <CircularProgress color="inherit" size={20} />
                        ) : null}
                        {params.InputProps.endAdornment}
                      </>
                    ),
                  }}
                />
              )}
            />
            {/*<TextField
              fullWidth
              label="Address"
              name="address"
              value={editedAttorney.address}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.address}
              helperText={formErrors.address}
            />*/}
          </Grid>
          <Grid size={{ xs: 12, sm: 4 }}>
            <TextField
              fullWidth
              label="City"
              name="city"
              value={editedAttorney.city}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.city}
              helperText={formErrors.city}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4 }}>
            <TextField
              fullWidth
              label="State"
              name="state"
              value={editedAttorney.state}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.state}
              helperText={formErrors.state}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4 }}>
            <TextField
              fullWidth
              label="Zip Code"
              name="zip_code"
              value={editedAttorney.zip_code}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.zip_code}
              helperText={formErrors.zip_code}
            />
          </Grid>
          {/*<Grid item xs={12}>
            <TextField
              fullWidth
              label="Specialties (comma-separated)"
              name="specialties"
              value={editedAttorney.specialties.join(', ')}
              onChange={(e) => handleArrayChange(e, 'specialties')}
              disabled={!isEditing}
            />
            <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {editedAttorney.specialties.map((specialty, index) => (
                <Chip key={index} label={specialty} size="small" />
              ))}
            </Box>
          </Grid>*/}
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Years of Experience"
              name="years_experience"
              type="number"
              value={editedAttorney.years_experience || ''}
              onChange={handleNumericChange}
              disabled={!isEditing}
              error={!!formErrors.years_experience}
              helperText={formErrors.years_experience}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Licensed States (comma-separated)"
              name="licensed_states"
              value={editedAttorney.licensed_states.join(', ')}
              onChange={(e) => handleArrayChange(e, 'licensed_states')}
              disabled={!isEditing}
            />
            <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
              {editedAttorney.licensed_states.map((state, index) => (
                <Chip key={index} label={state} size="small" variant="outlined" />
              ))}
            </Box>
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Website URL"
              name="website"
              value={editedAttorney.website || ''}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Biography"
              name="bio"
              multiline
              rows={4}
              value={editedAttorney.bio || ''}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <Button
              variant="contained"
              component="label"
              startIcon={<AddPhotoAlternateIcon />}
              disabled={!isEditing}
            >
              Upload Profile Picture
              <input type="file" hidden accept="image/*" onChange={handleProfilePictureUpload} />
            </Button>
          </Grid>
          <Grid size={{ xs: 12 }}>
            <Typography variant="subtitle1">
              Subscription Tier: {attorney.user.tier === 'premium' ? 'Premium' : 'Basic'}
            </Typography>
            {attorney.user.tier === 'basic' && (
              <Button
                variant="contained"
                color="primary"
                onClick={onUpgrade}
                sx={{ mt: 1 }}
                disabled={isEditing}
              >
                Upgrade to Premium
              </Button>
            )}
          </Grid>
          {editedAttorney.latitude && editedAttorney.longitude && (
            <Grid size={{ xs: 12 }}>
              <Typography variant="subtitle1" gutterBottom>
                Firm Location on Map:
              </Typography>
              {/* Assuming MapComponent accepts center, zoom, and a single property for display */}
              <MapComponent
                lat={editedAttorney.latitude}
                lng={editedAttorney.longitude}
                address={editedAttorney.address}
              />
            </Grid>
          )}
        </Grid>
        {Object.keys(formErrors).length > 0 && (
          <Alert severity="error" sx={{ mt: 2 }}>
            Please correct the errors in the form.
          </Alert>
        )}
      </CardContent>
    </Card>
  );
};

export default AttorneyProfileCard;
