import { AuthService } from './auth-service';
import { useAuthStore } from './auth-store';

export interface ProfileData {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone?: string;
  userType: string;
  profileImage?: string;
  isActive: boolean;
  language?: 'es' | 'en';
  createdAt: Date;
  lastLogin?: Date;
  doctor?: {
    signatureUrl?: string;
    specialization?: string;
    licenseNumber?: string;
    logoUrl?: string;
    isDentist?: boolean;
  };
  clinic?: {
    name?: string;
    address?: string;
    phone?: string;
  };
}

export interface UpdateProfileRequest {
  firstName?: string;
  lastName?: string;
  phone?: string;
  profileImage?: string;
  language?: 'es' | 'en';
  specialization?: string;
  licenseNumber?: string;
  clinic?: {
    name?: string;
    address?: string;
    phone?: string;
  };
}

export interface ChangePasswordRequest {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

export class ProfileService {
  static async getProfile(): Promise<{ success: boolean; user?: ProfileData; error?: string }> {
    try {
      const token = AuthService.getToken();
      if (!token) {
        return {
          success: false,
          error: 'No authentication token found',
        };
      }

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/profile`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token }),
      });

      const result = await response.json();
      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static async updateProfile(data: UpdateProfileRequest): Promise<{ success: boolean; user?: ProfileData; message?: string; error?: string }> {
    try {
      const token = AuthService.getToken();
      if (!token) {
        return {
          success: false,
          error: 'No authentication token found',
        };
      }

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/update-profile`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token, ...data }),
      });

      const result = await response.json();

      if (result.success && result.user) {
        // Preserve existing doctor/dentist fields when update-profile returns partial user data
        const currentUser = useAuthStore.getState().user;
        const incomingUser = result.user as ProfileData & { isDentist?: boolean };
        const mergedUser = {
          ...(currentUser || {}),
          ...incomingUser,
          doctor: incomingUser.doctor ?? currentUser?.doctor,
          clinic: incomingUser.clinic ?? currentUser?.clinic,
          isDentist: incomingUser.isDentist ?? incomingUser.doctor?.isDentist ?? currentUser?.isDentist,
        };

        useAuthStore.getState().updateUser(mergedUser);
      }

      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    }
  }

  static async changePassword(data: ChangePasswordRequest): Promise<{ success: boolean; message?: string; error?: string }> {
    try {
      const token = AuthService.getToken();
      if (!token) {
        return {
          success: false,
          error: 'No authentication token found',
        };
      }

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/change-password`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token, ...data }),
      });

      const result = await response.json();
      return result;
    } catch (error: any) {
      return {
        success: false,
        error: error.message || 'Network error',
      };
    };
  }

  static async uploadProfileImage(file: File): Promise<{ success: boolean; filePath?: string; error?: string }> {
    try {
      const token = AuthService.getToken();
      if (!token) {
        return { success: false, error: 'No authentication token found' };
      }

      // Get user ID from token (decode it) or fetch profile first to get ID
      // Since we don't have a good way to decode JWT client-side without a library here easily, 
      // and the backend upload controller expects userId in body (which is a bit weird for a protected route, but sticking to plan),
      // we should probably fetch the profile to get the ID, or just change backend to use the token.

      // actually, let's fetch profile first if we don't have the user ID stored.
      // But wait, the auth store should have the user.
      const user = useAuthStore.getState().user;
      if (!user) {
        return { success: false, error: 'User not logged in' };
      }

      const formData = new FormData();
      formData.append('profileImage', file);
      formData.append('userId', user.id);

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/upload/profile-image`, {
        method: 'POST',
        // Content-Type header is set automatically by browser with boundary for FormData
        body: formData,
      });

      const result = await response.json();

      if (result.success && result.user) {
        // Update local state
        const currentUser = useAuthStore.getState().user;
        if (currentUser) {
          useAuthStore.getState().updateUser({ ...currentUser, profileImage: result.user.profileImage });
        }
      }

      return result;
    } catch (error: any) {
      return { success: false, error: error.message || 'Upload failed' };
    }
  }

  static async uploadSignature(file: File): Promise<{ success: boolean; filePath?: string; error?: string }> {
    try {
      const token = AuthService.getToken();
      if (!token) return { success: false, error: 'No authentication token found' };

      const user = useAuthStore.getState().user;
      if (!user) return { success: false, error: 'User not logged in' };

      const formData = new FormData();
      formData.append('signature', file);
      formData.append('userId', user.id);

      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/upload/signature`, {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (result.success && result.doctor) {
        const currentUser = useAuthStore.getState().user;
        if (currentUser) {
          useAuthStore.getState().updateUser({
            ...currentUser,
            doctor: {
              ...(currentUser.doctor || {}),
              signatureUrl: result.doctor.signatureUrl,
            },
          });
        }
      }

      return result;
    } catch (error: any) {
      return { success: false, error: error.message || 'Upload failed' };
    }
  }
}
