import 'dart:io';
import 'dart:ui';


import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:bookmywages/viewmodel/consts_api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

class VendorProfileMain extends ConsumerStatefulWidget {
  const VendorProfileMain({super.key});

  @override
  ConsumerState<VendorProfileMain> createState() => _VendorProfileMainState();
}

class _VendorProfileMainState extends ConsumerState<VendorProfileMain> {
  File? _image;
  final ImagePicker _picker = ImagePicker();
  bool _isProfileDataInitialized = false;
  bool _isUploading = false;

  final TextStyle gilroyTextStyle = const TextStyle(
    fontFamily: 'Gilroy-Bold',
    fontWeight: FontWeight.w700,
    fontSize: 20,
    height: 1.45,
    letterSpacing: 0.01,
  );

  // Modified _pickImage method with automatic API upload using existing repository
  Future<void> _pickImage() async {
    try {
      final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
      if (pickedFile != null) {
        setState(() {
          _image = File(pickedFile.path);
          _isUploading = true;
        });

        // Automatically upload to API using existing repository
        await _uploadImageToAPI(File(pickedFile.path));
      }
    } catch (e) {
      debugPrint('Error picking image: $e');
      _showErrorToast('Failed to pick image: $e');
    }
  }

  // Upload image using existing ProfileupdateRepository
  Future<void> _uploadImageToAPI(File imageFile) async {
    try {
      // Get current profile data
      final profileData = ref.read(profilegetvendorProvider);

      await profileData.when(
        data: (profiles) async {
          if (profiles.isNotEmpty) {
            final profile = profiles[0];

            // Get the repository
            final repository = ref.read(profileupdatevendorRepositoryProvider);

            // Update profile with new image and existing data
            await repository.updateProfilevendor(
              url: ConstsApi.upadatevendorprofile,
              name: profile.name ?? '',
              number: profile.number ?? '',
              email: profile.email ?? '',
              address: profile.address ?? '',
              imageFile: imageFile,
            );

            // Refresh profile data to get updated image URL
            ref.invalidate(profilegetvendorProvider);

            _showSuccessToast('Profile picture updated successfully!');

            // Clear local image since it's now uploaded
            if (mounted) {
              setState(() {
                _image = null;
              });
            }
          } else {
            _showErrorToast('No profile data available');
            if (mounted) {
              setState(() {
                _image = null;
              });
            }
          }
        },
        loading: () async {
          _showErrorToast('Profile data is still loading');
          if (mounted) {
            setState(() {
              _image = null;
            });
          }
        },
        error: (error, _) async {
          _showErrorToast('Error getting profile data: $error');
          if (mounted) {
            setState(() {
              _image = null;
            });
          }
        },
      );
    } catch (e) {
      debugPrint('Error uploading image: $e');
      _showErrorToast('Upload failed: $e');
      if (mounted) {
        setState(() {
          _image = null;
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isUploading = false;
        });
      }
    }
  }

  // Helper methods for showing toasts
  void _showSuccessToast(String message) {
    if (mounted) {
      Fluttertoast.showToast(
        msg: message,
        backgroundColor: Colors.green,
        textColor: Colors.white,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
    }
  }

  void _showErrorToast(String message) {
    if (mounted) {
      Fluttertoast.showToast(
        msg: message,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.BOTTOM,
      );
    }
  }

  // Helper method to validate and construct image URL
  String? _getValidImageUrl(String? imageUrl) {
    if (imageUrl == null || imageUrl.isEmpty) {
      return null;
    }

    // Check if URL is complete (has a filename)
    if (imageUrl.endsWith('/') || imageUrl.endsWith('/images/')) {
      return null;
    }

    // Ensure URL is properly formatted
    if (!imageUrl.startsWith('http')) {
      return null;
    }

    return imageUrl;
  }

  // Helper widget for safe network image loading
  Widget _buildNetworkImage(String? imageUrl, {BoxFit fit = BoxFit.cover}) {
    final validUrl = _getValidImageUrl(imageUrl);

    if (validUrl == null) {
      return Image.asset(AppAssets.profile, fit: fit);
    }

    return Image.network(
      validUrl,
      fit: fit,
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) return child;
        return Center(
          child: CircularProgressIndicator(
            value:
                loadingProgress.expectedTotalBytes != null
                    ? loadingProgress.cumulativeBytesLoaded /
                        loadingProgress.expectedTotalBytes!
                    : null,
          ),
        );
      },
      errorBuilder: (context, error, stackTrace) {
        debugPrint('Error loading image: $error');
        return Image.asset(AppAssets.profile, fit: fit);
      },
    );
  }

  // Helper method for CircleAvatar image provider
  ImageProvider _getAvatarImageProvider(String? imageUrl) {
    if (_image != null) {
      return FileImage(_image!);
    }

    final validUrl = _getValidImageUrl(imageUrl);
    if (validUrl != null) {
      return NetworkImage(validUrl);
    }

    return const AssetImage(AppAssets.profile);
  }

  void _showSignOutDialog() {
    if (!mounted) return;

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Sign Out'),
          content: const Text('Are you sure you want to sign out?'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop();
                final prefs = await SharedPreferences.getInstance();
                await prefs.remove('userId');
                await prefs.remove('vendor_id');
                await prefs.remove('data');

                if (context.mounted) {
                  // context.go(
                  //   RouterConts.loginpage,
                  // ); // or use pushReplacement if needed
                }
              },
              child: const Text('Sign Out'),
            ),
          ],
        );
      },
    );
  }

  Widget _buildMenuItem(IconData icon, String title) {
    return ListTile(
      leading: Icon(
        icon,
        size: 23.000513076782227,
        color: const Color(0xFF3E3E3F),
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontFamily: 'Gilroy-Bold',
          fontWeight: FontWeight.w700,
          fontSize: 18,
          height: 1.0,
          letterSpacing: 0.2,
          color: Color(0xFF3E3E3F),
        ),
      ),
      trailing: const Icon(Icons.arrow_forward_ios_rounded),
      onTap: () async {
        try {
          if (title == 'My Profile') {
            await Get.toNamed(RouterConts.vendoreditprofile);
          } else if (title == 'Change Password') {
            // await context.push(RouterConts.changepassword);
          } else if (title == 'Sign out') {
            _showSignOutDialog();
          } else if (title == 'Terms and Conditions') {
            _showTermsAndConditionsDialog(ref); // Call the new dialog
          } else if (title == 'Privacy policy') {
            _showprivacyDialog(ref); // Call the new dialog
          }
          // Add other navigation cases as needed
        } catch (e) {
          debugPrint('Navigation error: $e');
          if (mounted) {
            _showErrorToast('Navigation error: $e');
          }
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      body: SafeArea(
        child: Column(
          children: [
            Flexible(
              flex: 1,
              child: Stack(
                children: [
                  SizedBox(
                    width: double.infinity,
                    height: height * 0.4,
                    child: Consumer(
                      builder: (context, ref, _) {
                        final profileData = ref.watch(profilegetvendorProvider);
                        return profileData.when(
                          data: (profiles) {
                            final profile =
                                profiles.isNotEmpty ? profiles[0] : null;

                            if (profile != null && !_isProfileDataInitialized) {
                              WidgetsBinding.instance.addPostFrameCallback((_) {
                                if (mounted) {
                                  setState(() {
                                    _isProfileDataInitialized = true;
                                  });
                                }
                              });
                            }

                            return _image == null
                                ? _buildNetworkImage(profile?.profilePic1)
                                : Image.file(_image!, fit: BoxFit.cover);
                          },
                          loading:
                              () => const Center(
                                child: CircularProgressIndicator(),
                              ),
                          error:
                              (error, _) => Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    const Icon(Icons.error, size: 50),
                                    Text('Error loading profile: $error'),
                                  ],
                                ),
                              ),
                        );
                      },
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    child: CustomPaint(
                      size: Size(width, height * 0.4),
                      painter: RightToLeftFullWidthTrianglePainter(),
                    ),
                  ),
                  Positioned(
                    bottom: height * 0.03,
                    left: width / 2 - 170,
                    child: Consumer(
                      builder: (context, ref, _) {
                        final profileData = ref.watch(profilegetvendorProvider);
                        return profileData.when(
                          data: (profiles) {
                            final profile =
                                profiles.isNotEmpty ? profiles[0] : null;
                            return Stack(
                              alignment: Alignment.center,
                              children: [
                                CircleAvatar(
                                  radius: 68,
                                  backgroundColor: Colors.white,
                                  child: CircleAvatar(
                                    radius: 65,
                                    backgroundImage: _getAvatarImageProvider(
                                      profile?.profilePic1,
                                    ),
                                    onBackgroundImageError: (
                                      error,
                                      stackTrace,
                                    ) {
                                      debugPrint('Avatar image error: $error');
                                    },
                                  ),
                                ),
                                // Show upload progress indicator
                                if (_isUploading)
                                  Container(
                                    width: 136,
                                    height: 136,
                                    decoration: BoxDecoration(
                                      color: Colors.black.withOpacity(0.5),
                                      shape: BoxShape.circle,
                                    ),
                                    child: const Center(
                                      child: CircularProgressIndicator(
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                              ],
                            );
                          },
                          loading:
                              () => const CircleAvatar(
                                radius: 68,
                                backgroundColor: Colors.white,
                                child: CircleAvatar(
                                  radius: 65,
                                  child: CircularProgressIndicator(),
                                ),
                              ),
                          error:
                              (error, _) => const CircleAvatar(
                                radius: 68,
                                backgroundColor: Colors.white,
                                child: CircleAvatar(
                                  radius: 65,
                                  backgroundImage: AssetImage(
                                    AppAssets.profile,
                                  ),
                                ),
                              ),
                        );
                      },
                    ),
                  ),
                  Positioned(
                    bottom: height * 0.08,
                    left: width / 2 - 20,
                    child: Consumer(
                      builder: (context, ref, _) {
                        final profileData = ref.watch(profilegetvendorProvider);
                        return profileData.when(
                          data: (profiles) {
                            final profile =
                                profiles.isNotEmpty ? profiles[0] : null;
                            if (profile == null) {
                              return Text(
                                'No Profile Data',
                                style: gilroyTextStyle,
                              );
                            }
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text(
                                      profile.name ?? 'No Name',
                                      style: gilroyTextStyle,
                                    ),
                                    IconButton(
                                      onPressed:
                                          _isUploading ? null : _pickImage,
                                      icon:
                                          _isUploading
                                              ? const SizedBox(
                                                width: 16,
                                                height: 16,
                                                child:
                                                    CircularProgressIndicator(
                                                      strokeWidth: 2,
                                                    ),
                                              )
                                              : const Icon(Icons.edit),
                                    ),
                                  ],
                                ),
                                Row(
                                  children: [
                                    const Icon(Icons.location_city, size: 20),
                                    const SizedBox(width: 4),
                                    Text(
                                      profile.address ?? 'No address available',
                                      style: const TextStyle(fontSize: 12),
                                    ),
                                  ],
                                ),
                              ],
                            );
                          },
                          loading: () => const CircularProgressIndicator(),
                          error:
                              (error, _) =>
                                  Text('Error: $error', style: gilroyTextStyle),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 30),
            Expanded(
              flex: 1,
              child: ListView(
                shrinkWrap: true,
                children: [
                  _buildMenuItem(Icons.person, 'My Profile'),

                  _buildMenuItem(Icons.notifications, 'Notification'),
                  _buildMenuItem(Icons.safety_check, 'Privacy policy'),
                  _buildMenuItem(Icons.description, 'Terms and Conditions'),
                  _buildMenuItem(Icons.logout, 'Sign out'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showTermsAndConditionsDialog(WidgetRef ref) {
    if (!mounted) return;

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
          child: Dialog(
            backgroundColor: Colors.transparent,
            insetPadding: const EdgeInsets.all(20),
            child: Center(
              child: Consumer(
                builder: (context, ref, _) {
                  final termsAsync = ref.watch(termsAndConditionsProvider);

                  return termsAsync.when(
                    data:
                        (terms) => Container(
                          width: 389,
                          height: 547,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                              color: const Color(0xFF959595),
                              width: 1,
                            ),
                          ),
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Center(
                                child: Text(
                                  "Terms & Condition",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18,
                                  ),
                                ),
                              ),
                              const SizedBox(height: 12),
                              Expanded(
                                child: ScrollbarTheme(
                                  data: ScrollbarThemeData(
                                    thumbColor: WidgetStateProperty.all(
                                      AppColors.primary,
                                    ),
                                    trackColor: WidgetStateProperty.all(
                                      Colors.transparent,
                                    ),
                                    trackBorderColor: WidgetStateProperty.all(
                                      Colors.transparent,
                                    ),
                                    thickness: WidgetStateProperty.all(13),
                                    radius: const Radius.circular(19),
                                    thumbVisibility: WidgetStateProperty.all(
                                      true,
                                    ),
                                  ),
                                  child: Scrollbar(
                                    thumbVisibility: true,
                                    interactive: true,
                                    thickness: 13,
                                    radius: const Radius.circular(19),
                                    child: ListView(
                                      children: [
                                        Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              terms.data,
                                              style: const TextStyle(
                                                color: Colors.black,
                                              ),
                                            ),
                                            const SizedBox(height: 20),
                                            Center(
                                              child: SizedBox(
                                                width: 228,
                                                height: 51.82,
                                                child: ElevatedButton(
                                                  onPressed: () {
                                                    Navigator.pop(context);
                                                  },
                                                  style: ElevatedButton.styleFrom(
                                                    backgroundColor:
                                                        const Color(0xFF0066FF),
                                                    shape: RoundedRectangleBorder(
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                            22.95,
                                                          ),
                                                    ),
                                                  ),
                                                  child: const Text(
                                                    "OK",
                                                    textAlign: TextAlign.center,
                                                    style: TextStyle(
                                                      fontFamily: 'Poppins',
                                                      fontWeight:
                                                          FontWeight.w500,
                                                      fontSize: 18.87,
                                                      height: 23.59 / 18.87,
                                                      letterSpacing: -0.59,
                                                      color: Colors.white,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                    loading:
                        () => const Center(child: CircularProgressIndicator()),
                    error:
                        (e, _) => Container(
                          padding: const EdgeInsets.all(16),
                          child: Text(
                            "Error: ${e.toString()}",
                            style: const TextStyle(color: Colors.red),
                          ),
                        ),
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }

  void _showprivacyDialog(WidgetRef ref) {
    if (!mounted) return;

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
          child: Dialog(
            backgroundColor: Colors.transparent,
            insetPadding: const EdgeInsets.all(20),
            child: Center(
              child: Consumer(
                builder: (context, ref, _) {
                  final privacyAsync = ref.watch(privacypolicyProvider);

                  return privacyAsync.when(
                    data:
                        (terms) => Container(
                          width: 389,
                          height: 547,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                              color: const Color(0xFF959595),
                              width: 1,
                            ),
                          ),
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Center(
                                child: Text(
                                  "Privacy policy",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18,
                                  ),
                                ),
                              ),
                              const SizedBox(height: 12),
                              Expanded(
                                child: ScrollbarTheme(
                                  data: ScrollbarThemeData(
                                    thumbColor: WidgetStateProperty.all(
                                      AppColors.primary,
                                    ),
                                    trackColor: WidgetStateProperty.all(
                                      Colors.transparent,
                                    ),
                                    trackBorderColor: WidgetStateProperty.all(
                                      Colors.transparent,
                                    ),
                                    thickness: WidgetStateProperty.all(13),
                                    radius: const Radius.circular(19),
                                    thumbVisibility: WidgetStateProperty.all(
                                      true,
                                    ),
                                  ),
                                  child: Scrollbar(
                                    thumbVisibility: true,
                                    interactive: true,
                                    thickness: 13,
                                    radius: const Radius.circular(19),
                                    child: ListView(
                                      children: [
                                        Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              terms.data,
                                              style: const TextStyle(
                                                color: Colors.black,
                                              ),
                                            ),
                                            const SizedBox(height: 20),
                                            Center(
                                              child: SizedBox(
                                                width: 228,
                                                height: 51.82,
                                                child: ElevatedButton(
                                                  onPressed: () {
                                                    Navigator.pop(context);
                                                  },
                                                  style: ElevatedButton.styleFrom(
                                                    backgroundColor:
                                                        const Color(0xFF0066FF),
                                                    shape: RoundedRectangleBorder(
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                            22.95,
                                                          ),
                                                    ),
                                                  ),
                                                  child: const Text(
                                                    "OK",
                                                    textAlign: TextAlign.center,
                                                    style: TextStyle(
                                                      fontFamily: 'Poppins',
                                                      fontWeight:
                                                          FontWeight.w500,
                                                      fontSize: 18.87,
                                                      height: 23.59 / 18.87,
                                                      letterSpacing: -0.59,
                                                      color: Colors.white,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                    loading:
                        () => const Center(child: CircularProgressIndicator()),
                    error:
                        (e, _) => Container(
                          padding: const EdgeInsets.all(16),
                          child: Text(
                            "Error: ${e.toString()}",
                            style: const TextStyle(color: Colors.red),
                          ),
                        ),
                  );
                },
              ),
            ),
          ),
        );
      },
    );
  }
}

class RightToLeftFullWidthTrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Colors.white;

    final path = Path();
    path.moveTo(size.width, 0); // top right corner
    path.lineTo(size.width, size.height); // bottom right corner
    path.lineTo(0, size.height); // bottom left (tip)
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
