import React, { useState, useMemo } from "react";
import { View, ScrollView, TextInput, Alert } from "react-native";
import { AppContainer, MyButton, MyText, tw , BottomDialog } from "common-ui";
import RegistrationForm from "@/components/registration-form";
import { useUserDetails, useAuth } from "@/src/contexts/AuthContext";
import { useUpdateProfile } from "@/src/api-hooks/auth.api";
import { router } from "expo-router";
import { trpc } from '@/src/trpc-client';

function EditProfile() {
  const userDetails = useUserDetails();
  const { updateUserDetails, logout } = useAuth();
  const updateProfileMutation = useUpdateProfile();
  
  // State for mobile verification modal
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [enteredMobile, setEnteredMobile] = useState('');
  const deleteAccountMutation = trpc.user.auth.deleteAccount.useMutation();
  
  // Prevent unnecessary re-renders
  const mobileInputValue = useMemo(() => enteredMobile, [enteredMobile]);

  const handleUpdate = async (data: FormData) => {
    try {
      const response = await updateProfileMutation.mutateAsync(data);

      // Update the context with new user details
      if (response.user) {
        updateUserDetails(response.user);
      }

      // Navigate back to profile/me page
      router.replace('/(drawer)/(tabs)/me');
    } catch (error) {
      JSON.stringify(error);
      console.error('Update profile error:', error);
      throw error;
    }
  };

  const handleDeleteAccount = () => {
    setShowDeleteModal(true);
  };

  const confirmDeleteAccount = async () => {
    if (!enteredMobile.trim()) {
      Alert.alert('Error', 'Please enter your mobile number');
      return;
    }

    try {
      await deleteAccountMutation.mutateAsync({ mobile: enteredMobile });
      
      Alert.alert(
        'Account Deleted',
        'Your account and all data have been successfully deleted.',
        [
          {
            text: 'OK',
            onPress: () => {
              setShowDeleteModal(false);
              logout();
            }
          }
        ]
      );
    } catch (error: any) {
      Alert.alert(
        'Verification Failed',
        error?.message || 'Failed to delete account. Please check your mobile number.'
      );
    }
  };

  // Prepare initial values from user details
  const initialValues = userDetails ? {
    name: userDetails.name || '',
    email: userDetails.email || '',
    mobile: userDetails.mobile || '',
    profileImageUri: userDetails.profileImage || undefined,
  } : undefined;

  return (
    <AppContainer>
      <View style={tw`flex-1 justify-center px-4 py-8`}>
        <View style={tw`mb-8 mt-4`}>
          <MyText
            weight="bold"
            style={tw`text-3xl mb-2 text-center text-gray-800`}
          >
            Edit Profile
          </MyText>
          <MyText style={tw`text-base text-center text-gray-600`}>
            Update your account details
          </MyText>
        </View>

        <RegistrationForm
          onSubmit={handleUpdate}
          isEdit={true}
          initialValues={initialValues}
          isLoading={updateProfileMutation.isPending}
        />

        <View style={tw`mt-8`}>
          <MyButton
            textContent="Logout"
            onPress={logout}
            fillColor="gray1"
            textColor="error"
            fullWidth
          />
        </View>

        <View style={tw`mt-4`}>
          <MyButton
            textContent="Delete Me and My Data"
            onPress={handleDeleteAccount}
            fillColor="error"
            fullWidth
          />
        </View>

        {showDeleteModal && (
          <BottomDialog
            open={showDeleteModal}
            onClose={() => setShowDeleteModal(false)}
            enableDismiss={false}
          >
            <View style={tw`p-4`}>
              <MyText weight="bold" style={tw`text-xl mb-4 text-center text-red-600`}>
                ⚠️ Delete Account Permanently
              </MyText>
              
              <MyText style={tw`text-base mb-4 text-center text-gray-700`}>
                This action cannot be undone. All your data will be permanently deleted.
              </MyText>
              
              <MyText style={tw`text-sm mb-4 text-gray-600`}>
                Enter your registered mobile number to confirm:
              </MyText>
              
              <View style={tw`mb-6`}>
                <TextInput
                  value={mobileInputValue}
                  onChangeText={setEnteredMobile}
                  placeholder="Enter mobile number"
                  keyboardType="phone-pad"
                  style={tw`border border-gray-300 rounded-lg p-3 w-full h-12 bg-white`}
                  maxLength={15}
                  selectTextOnFocus={true}
                  clearButtonMode="while-editing"
                />
              </View>
              
              <View style={tw`flex-row gap-3`}>
                <View style={tw`flex-1`}>
                  <MyButton
                    textContent="Cancel"
                    onPress={() => setShowDeleteModal(false)}
                    fillColor="gray1"
                    textColor="gray700"
                    fullWidth
                  />
                </View>
                <View style={tw`flex-1`}>
                  <MyButton
                    textContent="Delete Forever"
                    onPress={confirmDeleteAccount}
                    fillColor="error"
                    fullWidth
                    loading={deleteAccountMutation.isPending}
                  />
                </View>
              </View>
            </View>
          </BottomDialog>
        )}
      </View>
      </AppContainer>
  );
}

export default EditProfile;