import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
import 'package:taxglide/consts/app_asstes.dart';
import 'package:taxglide/consts/app_style.dart';
import 'package:taxglide/consts/download_helper.dart';
import 'package:taxglide/controller/api_consts.dart';
import 'package:taxglide/controller/api_contoller.dart';
import 'package:taxglide/router/consts_routers.dart';

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

  @override
  ConsumerState<KycDetailsList> createState() => _KycDetailsListState();
}

class _KycDetailsListState extends ConsumerState<KycDetailsList> {
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final profileAsync = ref.watch(profileProvider);

    return Scaffold(
      body: Container(
        height: size.height,
        width: size.width,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AppAssets.backgroundimages),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: profileAsync.when(
            data: (profile) {
              final data = profile.data;

              if (data == null) {
                return const Center(
                  child: Text(
                    "No KYC data found",
                    style: TextStyle(color: Colors.white),
                  ),
                );
              }

              return SingleChildScrollView(
                physics: const BouncingScrollPhysics(),
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 20,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 21),
                      child: SizedBox(
                        height: 50,
                        width: double.infinity,
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            const Text(
                              "KYC Details",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontFamily: "Gilroy",
                                fontWeight: FontWeight
                                    .w600, // equivalent to 400 (Normal)
                                fontStyle: FontStyle.normal,
                                fontSize: 24,
                                height: 1.3, // line-height: 130%
                                letterSpacing:
                                    0.04 * 24, // 4% of font size = 0.96px
                                color: Color(0xFF111827), // background: #111827
                              ),
                            ),

                            Positioned(
                              left: 0,
                              child: GestureDetector(
                                onTap: () => Get.back(),
                                child: const Icon(Icons.arrow_back_ios_rounded),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),

                    // White Card
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(18),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(14),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 6,
                            offset: const Offset(0, 3),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text(
                                "Personal Details",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontFamily: "Gilroy",
                                  fontWeight: FontWeight
                                      .w400, // equivalent to 400 (Normal)
                                  fontStyle: FontStyle.normal,
                                  fontSize: 20,
                                  height: 1.3, // line-height: 130%
                                  letterSpacing:
                                      0.04 * 20, // 4% of font size = 0.8px
                                  color: Color(
                                    0xFF111827,
                                  ), // background: #111827
                                ),
                              ),

                              GestureDetector(
                                onTap: () {
                                  Get.toNamed(ConstRouters.kycdetails);
                                },
                                child: Container(
                                  width: 109,
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 8,
                                    horizontal: 12,
                                  ),
                                  decoration: BoxDecoration(
                                    color: const Color(
                                      0xFFFFFFFF,
                                    ), // background: #FFFFFF
                                    borderRadius: BorderRadius.circular(
                                      8,
                                    ), // border-radius: 8px
                                    border: Border.all(
                                      color: const Color(
                                        0xFFE3E3E3,
                                      ), // border: 1px solid #E3E3E3
                                      width: 1,
                                    ),
                                    boxShadow: [
                                      BoxShadow(
                                        color: const Color(0xFF767373)
                                            .withOpacity(
                                              0.25,
                                            ), // #76737340 ≈ 25% opacity
                                        blurRadius: 10,
                                        offset: const Offset(0, 0),
                                      ),
                                    ],
                                  ),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment
                                        .center, // center horizontally
                                    crossAxisAlignment: CrossAxisAlignment
                                        .center, // center vertically
                                    children: const [
                                      Icon(
                                        Icons.edit_outlined,
                                        size: 18,
                                        color: Color(
                                          0xFF111827,
                                        ), // matches your text color
                                      ),
                                      SizedBox(width: 6),
                                      Text(
                                        'Edit',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontFamily: "Gilroy",
                                          fontWeight: FontWeight.w600,
                                          fontStyle: FontStyle.normal,
                                          fontSize: 16,
                                          height: 1.3, // 130%
                                          letterSpacing: 0.04 * 16, // 4%
                                          color: Color(0xFF111827),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 25),
                          _buildDetailRow('Company Name : ', data.companyName),
                          const SizedBox(height: 24),
                          _buildDetailRow('PAN Number : ', data.panNumber),
                          const SizedBox(height: 24),
                          _buildDetailRow('GST Number : ', data.gstNumber),
                          const SizedBox(height: 24),
                          _buildDetailRow(
                            'Year of Incorporation : ',
                            data.yearOfIncorporation?.toString(),
                          ),
                          const SizedBox(height: 24),
                          _buildDetailRow('Email : ', data.companyEmail),
                          const SizedBox(height: 24),
                          _buildDetailRow(
                            'Phone Number : ',
                            data.companyMobile,
                          ),
                          const SizedBox(height: 24),
                          _buildDetailRow('Address : ', data.companyAddress),
                          const SizedBox(height: 24),
                          _buildDetailRow('Country : ', data.countryName),
                          const SizedBox(height: 24),
                          _buildDetailRow('State : ', data.stateName),
                          const SizedBox(height: 24),
                          _buildDetailRow('City : ', data.districtName),
                          const SizedBox(height: 24),
                          _buildDetailRow('PinCode : ', data.companyPincode),
                        ],
                      ),
                    ),

                    const SizedBox(height: 30),

                    // 4 Image Containers
                    GridView.count(
                      crossAxisCount: 2,
                      crossAxisSpacing: 15,
                      mainAxisSpacing: 15,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      children: [
                        _buildImageBox("GST Certificate ", data.gstFile),
                        _buildImageBox("PAN File", data.panFile),

                        _buildImageBox(
                          "Incorporation File",
                          data.incorporationFile,
                        ),
                        _buildImageBox("Profile Image", data.logo),
                      ],
                    ),

                    const SizedBox(height: 40),
                  ],
                ),
              );
            },
            loading: () => const Center(
              child: CircularProgressIndicator(color: Colors.white),
            ),
            error: (e, st) => Center(
              child: Text(
                "Error loading KYC details: $e",
                style: const TextStyle(color: Colors.redAccent),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDetailRow(String title, String? value) {
    if (value == null || value.isEmpty) return const SizedBox.shrink();

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: AppTextStyles.semiBold.copyWith(
          
            fontSize: 14,
            height: 1.3,
            letterSpacing: 0.64,
            color: Colors.black87,
          ),
        ),
        Flexible(
          child: Text(
            value,
            softWrap: true,
            overflow: TextOverflow.visible,
            style: AppTextStyles.regular.copyWith(
            
              fontSize: 14,
              height: 1.3,
              letterSpacing: 0.64,
              color: Color(0xFF111827),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildImageBox(String label, String? imageUrl) {
    final fullUrl = imageUrl != null && imageUrl.isNotEmpty
        ? imageUrl.startsWith('http')
              ? imageUrl
              : "${ConstsApi.baseUrl}/api/$imageUrl"
        : null;

    final isDocument =
        label.toLowerCase().contains('gst') ||
        label.toLowerCase().contains('pan') ||
        label.toLowerCase().contains('incorporation');

    return Container(
      width: 175,
      height: 155,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 8,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            /// ✅ LABEL
            Text(
              label,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: AppTextStyles.semiBold.copyWith(
              
              
                fontSize: 13,
              ),
            ),

            const SizedBox(height: 8),

            /// ✅ IMAGE / DOCUMENT PREVIEW
            Expanded(
              child: InkWell(
                onTap: fullUrl == null
                    ? null
                    : () async {
                        await DownloadHelper.downloadFileToReceived(fullUrl);
                        setState(() {});
                      },
                child: Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade100,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: fullUrl != null
                        ? isDocument
                              ? const Center(
                                  child: Icon(
                                    Icons.insert_drive_file_rounded,
                                    size: 50,
                                    color: Colors.blueGrey,
                                  ),
                                )
                              : Image.network(
                                  fullUrl,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) =>
                                      const Center(
                                        child: Icon(Icons.broken_image),
                                      ),
                                )
                        : const Center(
                            child: Icon(Icons.image_not_supported, size: 40),
                          ),
                  ),
                ),
              ),
            ),

            const SizedBox(height: 8),

            /// ✅ DOWNLOAD / VIEW BUTTON
            if (fullUrl != null)
              FutureBuilder<String?>(
                future: DownloadHelper.checkFileExistsInReceived(fullUrl),
                builder: (context, snapshot) {
                  final existsPath = snapshot.data;

                  return SizedBox(
                    height: 36,
                    child: ElevatedButton.icon(
                      style: ElevatedButton.styleFrom(
                        elevation: 0,
                        backgroundColor: existsPath == null
                            ? Colors.blue
                            : Colors.green,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30),
                        ),
                      ),
                      onPressed: () async {
                        if (existsPath == null) {
                          await DownloadHelper.downloadFileToReceived(fullUrl);
                          setState(() {});
                        } else {
                          await DownloadHelper.openDownloadedFile(existsPath);
                        }
                      },
                      icon: Icon(
                        existsPath == null
                            ? Icons.download_rounded
                            : Icons.remove_red_eye_rounded,
                        size: 18,
                        color: Colors.white,
                      ),
                      label: Text(
                        existsPath == null ? "Download" : "View",
                        style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  );
                },
              ),
          ],
        ),
      ),
    );
  }
}
