import React, { useState, useEffect, ReactElement } from 'react';
import { Container, Typography, Box, Alert, CircularProgress } from '@mui/material';

import { AttorneyAPI, UserAPI } from '../../../../../types';
import ChangePasswordCard from './ChangePasswordCard';
import { ProfileProps } from 'pages/Profile/Profile';
import DashboardLoading from '../Dashboard/DashboardLoading';
import DashboardErrorPage from '../Dashboard/DashboardErrorPage';
import AttorneyProfileCard from './AttorneyProfileCard';
import { AxiosResponse } from 'axios';
import { axiosInstance } from '../../../../../axiosApi';
import { useNavigate } from 'react-router-dom';

const AttorneyProfile = ({ account }: ProfileProps): ReactElement => {
  const [attorney, setAttorney] = useState<AttorneyAPI | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const navigate = useNavigate();

  const fetchAttorneyData = async () => {
    setLoading(true);
    setError(null);
    try {
      const { data }: AxiosResponse<AttorneyAPI[]> = await axiosInstance.get('/attorney/');
      if (data.length > 0) {
        setAttorney(data[0]);
      }
      // setAttorney(initialAttorneyData);
    } catch (err: any) {
      setError(err.message || 'An error occurred while fetching profile data.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAttorneyData();
  }, []);

  const handleUpgradeSubscription = () => {
    if (attorney) {
      navigate('/upgrade/');
      //setAttorney((prev) => (prev ? { ...prev, user: { ...prev.user, tier: 'premium' } } : null));
      //setMessage({ type: 'success', text: 'Subscription upgraded to Premium!' });
      //setTimeout(() => setMessage(null), 3000);
    }
  };

  const handleSaveAttorneyProfile = (updatedAttorney: AttorneyAPI) => {
    // In a real application, you'd send this data to your backend API
    try {
      let newUpdatedAttorney;
      // if the email is the same, remove it
      if (updatedAttorney.user.email === account.email) {
        const { user, ...reducedVendor } = updatedAttorney;
        const { email, ...reducedUser } = user;
        newUpdatedAttorney = {
          user: {
            profile_created: true,
            ...reducedUser,
          },
          ...reducedVendor,
        };
      } else {
        newUpdatedAttorney = updatedAttorney;
      }
      newUpdatedAttorney.user.profile_created = true;
      console.log(newUpdatedAttorney);

      const { data, error } = axiosInstance.patch(`/attorney/${account.id}/`, {
        ...newUpdatedAttorney,
      });
      console.log(data, error);
      setAttorney({
        profile: { profile_created: true, ...updatedAttorney.profile },
        ...updatedAttorney,
      });
      setMessage({ type: 'success', text: 'Profile updated successfully!' });
      setTimeout(() => setMessage(null), 3000);
    } catch (error) {
      console.log(error);
      setMessage({ type: 'error', text: 'Error saving the profile. Try again.' });
      setTimeout(() => setMessage(null), 3000);
    }
    // console.log('Saving attorney profile:', updatedAttorney);
    // setAttorney(updatedAttorney);
    // setMessage({ type: 'success', text: 'Profile updated successfully!' });
    // setTimeout(() => setMessage(null), 3000);
  };

  if (loading) {
    return <DashboardLoading />;
  }

  if (error) {
    return <DashboardErrorPage />;
  }

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        Attorney Profile
      </Typography>
      {message && (
        <Alert severity={message.type} sx={{ mb: 2 }}>
          {message.text}
        </Alert>
      )}
      <AttorneyProfileCard
        attorney={attorney}
        onUpgrade={handleUpgradeSubscription}
        onSave={handleSaveAttorneyProfile}
      />

      {/*<Box sx={{ mt: 4 }}>
        <ChangePasswordCard />
      </Box>*/}
    </Container>
  );
};

export default AttorneyProfile;
