import 'dart:io';
import 'package:business_panel/core/config/app_colors.dart';
import 'package:business_panel/gen/assets.gen.dart';
import 'package:business_panel/presentation/pages/product_creation_landing_page.dart';
import 'package:business_panel/presentation/store_info/bloc/store_info_bloc.dart';
import 'package:business_panel/presentation/store_info/bloc/store_info_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:latlong2/latlong.dart';

class StoreInfoDisplayPage extends StatelessWidget {
  const StoreInfoDisplayPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildCustomAppBar(context),
      body: BlocListener<StoreInfoBloc, StoreInfoState>(
        listener: (context, state) {
          if (state.isSuccess) {
            Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(
                builder: (_) => const ProductCreationLandingPage(),
              ),
              (route) => false,
            );
          }
          if (state.errorMessage != null) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.errorMessage!),
                backgroundColor: Colors.red,
              ),
            );
          }
        },
        child: BlocBuilder<StoreInfoBloc, StoreInfoState>(
          builder: (context, state) {
            return SingleChildScrollView(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 10),
                _buildStoreLogo(state),
                const SizedBox(height: 24),
                Text(
                  state.storeName,
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 22,
                  ),
                ),
                const SizedBox(height: 12),
                if (state.activityType.isNotEmpty)
                  Container(
                    padding: const EdgeInsets.symmetric(
                      vertical: 8,
                      horizontal: 16,
                    ),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(15),
                    ),
                    child: Text(
                      state.activityType.split(' ').sublist(1).join(' '),
                      style: const TextStyle(fontSize: 16),
                    ),
                  ),
                const SizedBox(height: 8),
                TextButton.icon(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  icon: SvgPicture.asset(
                    Assets.icons.edit,
                    width: 20,
                    color: AppColors.button,
                  ),
                  label: const Text(
                    "ویرایش",
                    style: TextStyle(color: AppColors.button, fontSize: 16),
                  ),
                ),
                if (state.workingDays.isNotEmpty)
                  _buildInfoRow(
                    icon: Assets.icons.clock,
                    text:
                        "${state.workingDays.map((day) => _translateDay(day)).join('، ')}\nاز ساعت ${state.startTime} تا ${state.endTime}",
                  ),
                if (state.contactPhone != null &&
                    state.contactPhone!.isNotEmpty)
                  _buildInfoRow(
                    icon: Assets.icons.callCalling,
                    text: state.contactPhone!,
                  ),
                if (state.licenseNumber != null &&
                    state.licenseNumber!.isNotEmpty)
                  _buildInfoRow(
                    icon: Assets.icons.documentText,
                    text: "شماره جواز کسب ${state.licenseNumber!}",
                  ),
                if (state.address.isNotEmpty)
                  _buildInfoRow(
                    icon: Assets.icons.location,
                    text: state.address,
                  ),
                const SizedBox(height: 24),
                if (state.latitude != null && state.longitude != null)
                  _buildMapView(state.latitude!, state.longitude!),
                const SizedBox(height: 40),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                      onPressed: state.isSubmitting ? null : () {
                        context.read<StoreInfoBloc>().add(SubmitStoreInfo());
                      },
                      child: state.isSubmitting
                          ? const CircularProgressIndicator(color: Colors.white)
                          : const Text("ثبت"),
                    ),
                  ),
                const SizedBox(height: 24),
              ],
            ),
          );
        },
      ),
    ));
  }

  Widget _buildStoreLogo(StoreInfoState state) {
    return CircleAvatar(
      radius: 65,
      backgroundColor: AppColors.uploadElevated,
      backgroundImage:
          state.logoPath != null ? FileImage(File(state.logoPath!)) : null,
      child: null,
    );
  }

  Widget _buildInfoRow({required String icon, required String text}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12.0),
      child: Row(
        children: [
          SvgPicture.asset(
            icon,
            width: 24,
            color: Color.fromARGB(255, 161, 160, 160),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Text(
              text,
              style: const TextStyle(fontSize: 14, height: 1.5),
              textAlign: TextAlign.right,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMapView(double latitude, double longitude) {
    return SizedBox(
      height: 200,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(15),
        child: FlutterMap(
          options: MapOptions(
            initialCenter: LatLng(latitude, longitude),
            initialZoom: 15.0,
          ),
          children: [
            TileLayer(
              urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
            ),
            MarkerLayer(
              markers: [
                Marker(
                  width: 80.0,
                  height: 80.0,
                  point: LatLng(latitude, longitude),
                  child: const Icon(
                    Icons.location_on,
                    color: Colors.red,
                    size: 40.0,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  PreferredSizeWidget _buildCustomAppBar(BuildContext context) {
    return PreferredSize(
      preferredSize: const Size.fromHeight(70.0),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: const BorderRadius.vertical(
            bottom: Radius.circular(15),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 10,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Column(
              children: [
                const SizedBox(height: 15),
                Row(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(right: 8),
                      child: SvgPicture.asset(Assets.icons.logoWithName),
                    ),

                    const Spacer(),

                    Row(
                      children: [
                        IconButton(
                          onPressed: () {},
                          icon: SvgPicture.asset(
                            Assets.icons.discountShape,
                            color: Colors.black,
                          ),
                        ),
                        IconButton(
                          onPressed: () {},
                          icon: SvgPicture.asset(Assets.icons.scanBarcode),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  String _translateDay(String day) {
    const Map<String, String> dayTranslations = {
      'Saturday': 'شنبه',
      'Sunday': 'یکشنبه',
      'Monday': 'دوشنبه',
      'Tuesday': 'سه‌شنبه',
      'Wednesday': 'چهارشنبه',
      'Thursday': 'پنج‌شنبه',
      'Friday': 'جمعه',
    };
    return dayTranslations[day] ?? day;
  }
}
