import React, { useState } from 'react';
import {
  Card,
  CardContent,
  CircularProgress,
  Typography,
  Button,
  Grid,
  TextField,
  Box,
  Alert,
  IconButton,
  InputLabel,
  Select,
  MenuItem,
  FormControl,
  Autocomplete,
} 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 { VendorAPI, UserAPI } from '../types/api';
import { test_autocomplete } from 'data/mock_autocomplete_results';
import { AutocompleteDataResponseAPI } from 'types';
import { axiosInstance, axiosRealEstateApi } from '../../../../../axiosApi';
import { extractLatLon } from 'utils';
import { PlacePrediction } from './AddPropertyDialog';

interface VendorProfileCardProps {
  vendor: VendorAPI;
  onUpgrade: () => void;
  onSave: (updatedVendor: VendorAPI) => void;
}

const VendorProfileCard: React.FC<VendorProfileCardProps> = ({ vendor, onUpgrade, onSave }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editedVendor, setEditedVendor] = useState<VendorAPI>(vendor);
  const [formErrors, setFormErrors] = useState<{ [key: string]: string }>({});

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

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

  const handleChange = (
    e:
      | React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
      | React.ChangeEvent<{ name?: string; value: unknown }>,
  ) => {
    const { name, value } = e.target;
    setEditedVendor((prev) => ({
      ...prev,
      [name as string]: 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 as string]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name as string];
        return newErrors;
      });
    }
  };

  const validateForm = () => {
    const errors: { [key: string]: string } = {};
    if (!editedVendor.business_name.trim()) {
      errors.business_name = 'Business name is required.';
    }
    if (!editedVendor.phone_number.trim()) {
      errors.phone_number = 'Phone number is required.';
    } else if (!/^\d{10}$/.test(editedVendor.phone_number.replace(/\D/g, ''))) {
      errors.phone_number = 'Invalid phone number format (10 digits).';
    }
    if (!editedVendor.address.trim()) {
      errors.address = 'Address is required.';
    }
    if (!editedVendor.city.trim()) {
      errors.city = 'City is required.';
    }
    if (!editedVendor.state.trim()) {
      errors.state = 'State is required.';
    }
    if (!editedVendor.zip_code.trim()) {
      errors.zip_code = 'Zip code is required.';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

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

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    //setNewProperty((prev) => ({ ...prev, [name]: value }));
    if (formErrors[name]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  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,
  ) => {
    console.log('here we go', value);
    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);
        setEditedVendor((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
    }
  };

  return (
    <Card sx={{ mt: 3, p: 2 }}>
      <CardContent>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h5" gutterBottom>
            Vendor Profile Information
          </Typography>
          {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}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="First Name"
              name="first_name"
              value={editedVendor.user.first_name}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Last Name"
              name="last_name"
              value={editedVendor.user.last_name}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Email Address"
              name="email"
              type="email"
              value={editedVendor.user.email}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Business Name"
              name="business_name"
              value={editedVendor.business_name}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.business_name}
              helperText={formErrors.business_name}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <FormControl fullWidth disabled={!isEditing}>
              <InputLabel id="business-type-label">Business Type</InputLabel>
              <Select
                labelId="business-type-label"
                id="business_type"
                name="business_type"
                value={editedVendor.business_type}
                label="Business Type"
                onChange={handleChange}
              >
                <MenuItem value="electrician">Electrician</MenuItem>
                <MenuItem value="carpenter">Carpenter</MenuItem>
                <MenuItem value="plumber">Plumber</MenuItem>
                <MenuItem value="inspector">Inspector</MenuItem>
                <MenuItem value="lendor">Lendor</MenuItem>
                <MenuItem value="other">Other</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Phone Number"
              name="phone_number"
              value={editedVendor.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={editedVendor.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}
                      </>
                    ),
                  }}
                />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4 }}>
            <TextField
              fullWidth
              label="City"
              name="city"
              value={editedVendor.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={editedVendor.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={editedVendor.zip_code}
              onChange={handleChange}
              disabled={!isEditing}
              required
              error={!!formErrors.zip_code}
              helperText={formErrors.zip_code}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Business Description"
              name="description"
              multiline
              rows={3}
              value={editedVendor.description}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Website URL"
              name="website"
              value={editedVendor.website || ''}
              onChange={handleChange}
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Certifications (comma-separated)"
              name="certifications"
              value={editedVendor.certifications?.join(', ') || ''}
              onChange={(e) =>
                setEditedVendor((prev) => ({
                  ...prev,
                  certifications: e.target.value
                    .split(',')
                    .map((s) => s.trim())
                    .filter((s) => s),
                }))
              }
              disabled={!isEditing}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <Typography variant="subtitle1">
              Subscription Tier: {vendor.user.tier === 'premium' ? 'Premium' : 'Basic'}
            </Typography>
            {vendor.user.tier === 'basic' && (
              <Button
                variant="contained"
                color="primary"
                onClick={onUpgrade}
                sx={{ mt: 1 }}
                disabled={isEditing}
              >
                Upgrade to Premium
              </Button>
            )}
          </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 VendorProfileCard;
