// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// injection_site_tracker_screen.dart
// Screen for tracking injection sites and rotations
//
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/features/medication_tracker/models/medication.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/core/services/navigation/navigation_service.dart';

class InjectionSiteTrackerScreen extends ConsumerStatefulWidget {
  final InjectionSiteRotation? initialRotation;
  final Function(InjectionSiteRotation) onSave;

  const InjectionSiteTrackerScreen({
    super.key,
    this.initialRotation,
    required this.onSave,
  });

  @override
  ConsumerState<InjectionSiteTrackerScreen> createState() =>
      _InjectionSiteTrackerScreenState();
}

class _InjectionSiteTrackerScreenState
    extends ConsumerState<InjectionSiteTrackerScreen> {
  late InjectionBodyArea _selectedBodyArea;
  late List<InjectionSite> _sites;
  late int _currentSiteIndex;

  @override
  void initState() {
    super.initState();

    // Initialize with existing data or defaults
    _sites = widget.initialRotation?.sites.toList() ?? [];
    _currentSiteIndex = widget.initialRotation?.currentSiteIndex ?? 0;
    _selectedBodyArea =
        _sites.isNotEmpty ? _sites.first.bodyArea : InjectionBodyArea.abdomen;
  }

  void _addSite(int siteNumber) {
    setState(() {
      _sites.add(InjectionSite(
        siteNumber: siteNumber,
        bodyArea: _selectedBodyArea,
      ));
    });
  }

  void _removeSite(int index) {
    setState(() {
      _sites.removeAt(index);
      if (_currentSiteIndex >= _sites.length) {
        _currentSiteIndex = _sites.isEmpty ? 0 : _sites.length - 1;
      }
    });
  }

  void _saveRotation() {
    final rotation = InjectionSiteRotation(
      sites: _sites,
      currentSiteIndex: _currentSiteIndex,
    );
    widget.onSave(rotation);
    NavigationService.goBack(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Injection Site Tracker'),
        actions: [
          IconButton(
            icon: Icon(AppIcons.getIcon('save')),
            onPressed: _saveRotation,
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // Body area selector
          _buildBodyAreaSelector(),

          SharedWidgets.verticalSpace(AppTheme.cardSpacing),

          // Body diagram
          _buildBodyDiagram(),

          SharedWidgets.verticalSpace(AppTheme.cardSpacing),

          // Site list and rotation
          _buildSiteRotationSection(),
        ],
      ),
    );
  }

  Widget _buildBodyAreaSelector() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Select Body Area', style: AppTextStyles.titleMedium),
            SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
            Row(
              children: [
                // Abdomen option
                Expanded(
                  child: _buildBodyAreaOption(
                    title: 'Abdomen',
                    area: InjectionBodyArea.abdomen,
                    icon: Icons.circle_outlined,
                  ),
                ),
                SharedWidgets.horizontalSpace(AppTheme.doubleSpacing),
                // Thigh option
                Expanded(
                  child: _buildBodyAreaOption(
                    title: 'Thighs',
                    area: InjectionBodyArea.thigh,
                    icon: Icons.rectangle_outlined,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBodyAreaOption({
    required String title,
    required InjectionBodyArea area,
    required IconData icon,
  }) {
    final isSelected = area == _selectedBodyArea;

    return InkWell(
      onTap: () {
        setState(() {
          _selectedBodyArea = area;
        });
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          border: Border.all(
            color: isSelected ? AppColors.primary : AppColors.outline,
            width: isSelected ? 2 : 1,
          ),
          borderRadius: BorderRadius.circular(8),
          color: isSelected ? AppColors.primary.withAlpha(50) : null,
        ),
        child: Column(
          children: [
            Icon(
              icon,
              color: isSelected ? AppColors.primary : null,
              size: 32,
            ),
            SharedWidgets.verticalSpace(),
            Text(
              title,
              style: TextStyle(
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                color: isSelected ? AppColors.primary : null,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBodyDiagram() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Injection Sites', style: AppTextStyles.titleMedium),
            SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
            _selectedBodyArea == InjectionBodyArea.abdomen
                ? _buildAbdomenDiagram()
                : _buildThighDiagram(),
            SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
            const Text(
              'Tap on a numbered site to add it to your rotation schedule.',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAbdomenDiagram() {
    return Center(
      child: SizedBox(
        width: 300,
        height: 300,
        child: Stack(
          children: [
            // Background circle container
            Container(
              width: 300,
              height: 300,
              decoration: BoxDecoration(
                border: Border.all(color: AppColors.outline),
                borderRadius: BorderRadius.circular(150),
                color: AppColors.surface.withAlpha(80),
              ),
            ),

            // Navel indicator
            Center(
              child: Container(
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                  color: AppColors.outline,
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
            ),

            // Abdomen separator lines
            CustomPaint(
              size: const Size(300, 300),
              painter: AbdomenLinePainter(),
            ),

            // Left abdomen label
            Positioned(
              top: 140,
              left: 20,
              child: RotatedBox(
                quarterTurns: 3,
                child: Text(
                  'Left',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppColors.onSurfaceVariant,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),

            // Right abdomen label
            Positioned(
              top: 140,
              right: 20,
              child: RotatedBox(
                quarterTurns: 1,
                child: Text(
                  'Right',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppColors.onSurfaceVariant,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),

            // Upper abdomen label
            Positioned(
              top: 15,
              left: 130,
              child: Text(
                'Upper',
                style: TextStyle(
                  fontSize: 12,
                  color: AppColors.onSurfaceVariant,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),

            // Lower abdomen label
            Positioned(
              bottom: 15,
              left: 130,
              child: Text(
                'Lower',
                style: TextStyle(
                  fontSize: 12,
                  color: AppColors.onSurfaceVariant,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),

            // 16 Abdomen Sites - 4 in each quadrant
            // Upper Left Quadrant (Sites 1-4)
            _buildClickableSiteContainer(top: 60, left: 60, siteNumber: 1),
            _buildClickableSiteContainer(top: 60, left: 110, siteNumber: 2),
            _buildClickableSiteContainer(top: 95, left: 60, siteNumber: 3),
            _buildClickableSiteContainer(top: 95, left: 110, siteNumber: 4),

            // Upper Right Quadrant (Sites 5-8)
            _buildClickableSiteContainer(top: 60, right: 110, siteNumber: 5),
            _buildClickableSiteContainer(top: 60, right: 60, siteNumber: 6),
            _buildClickableSiteContainer(top: 95, right: 110, siteNumber: 7),
            _buildClickableSiteContainer(top: 95, right: 60, siteNumber: 8),

            // Lower Left Quadrant (Sites 9-12)
            _buildClickableSiteContainer(bottom: 95, left: 60, siteNumber: 9),
            _buildClickableSiteContainer(bottom: 95, left: 110, siteNumber: 10),
            _buildClickableSiteContainer(bottom: 60, left: 60, siteNumber: 11),
            _buildClickableSiteContainer(bottom: 60, left: 110, siteNumber: 12),

            // Lower Right Quadrant (Sites 13-16)
            _buildClickableSiteContainer(
                bottom: 95, right: 110, siteNumber: 13),
            _buildClickableSiteContainer(bottom: 95, right: 60, siteNumber: 14),
            _buildClickableSiteContainer(
                bottom: 60, right: 110, siteNumber: 15),
            _buildClickableSiteContainer(bottom: 60, right: 60, siteNumber: 16),
          ],
        ),
      ),
    );
  }

  Widget _buildThighDiagram() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Left thigh
          SizedBox(
            width: 110,
            height: 320,
            child: Stack(
              children: [
                // Background container
                Container(
                  width: 110,
                  height: 320,
                  decoration: BoxDecoration(
                    border: Border.all(color: AppColors.outline),
                    borderRadius: BorderRadius.circular(30),
                    color: AppColors.surface.withAlpha(80),
                  ),
                ),

                // Inner/Outer separator line
                Positioned(
                  top: 0,
                  bottom: 0,
                  right: 55,
                  child: Container(
                    width: 1,
                    color: AppColors.outline.withAlpha(128),
                  ),
                ),

                // Left thigh label
                Positioned(
                  top: 15,
                  left: 0,
                  right: 0,
                  child: Center(
                    child: Text(
                      'Left Thigh',
                      style: TextStyle(
                        fontSize: 12,
                        color: AppColors.onSurfaceVariant,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),

                // Outer label
                Positioned(
                  top: 150,
                  left: 10,
                  child: RotatedBox(
                    quarterTurns: 3,
                    child: Text(
                      'Outer',
                      style: TextStyle(
                        fontSize: 11,
                        color: AppColors.onSurfaceVariant,
                      ),
                    ),
                  ),
                ),

                // Inner label
                Positioned(
                  top: 150,
                  right: 10,
                  child: RotatedBox(
                    quarterTurns: 1,
                    child: Text(
                      'Inner',
                      style: TextStyle(
                        fontSize: 11,
                        color: AppColors.onSurfaceVariant,
                      ),
                    ),
                  ),
                ),

                // Fix click positions for thigh sites
                _buildClickableSiteContainer(top: 50, left: 15, siteNumber: 1),
                _buildClickableSiteContainer(top: 50, right: 15, siteNumber: 2),
                _buildClickableSiteContainer(top: 110, left: 15, siteNumber: 3),
                _buildClickableSiteContainer(
                    top: 110, right: 15, siteNumber: 4),
                _buildClickableSiteContainer(top: 170, left: 15, siteNumber: 5),
                _buildClickableSiteContainer(
                    top: 170, right: 15, siteNumber: 6),
                _buildClickableSiteContainer(top: 230, left: 15, siteNumber: 7),
                _buildClickableSiteContainer(
                    top: 230, right: 15, siteNumber: 8),
              ],
            ),
          ),

          const SizedBox(width: 30),

          // Right thigh
          SizedBox(
            width: 110,
            height: 320,
            child: Stack(
              children: [
                // Background container
                Container(
                  width: 110,
                  height: 320,
                  decoration: BoxDecoration(
                    border: Border.all(color: AppColors.outline),
                    borderRadius: BorderRadius.circular(30),
                    color: AppColors.surface.withAlpha(80),
                  ),
                ),

                // Inner/Outer separator line
                Positioned(
                  top: 0,
                  bottom: 0,
                  left: 55,
                  child: Container(
                    width: 1,
                    color: AppColors.outline.withAlpha(128),
                  ),
                ),

                // Right thigh label
                Positioned(
                  top: 15,
                  left: 0,
                  right: 0,
                  child: Center(
                    child: Text(
                      'Right Thigh',
                      style: TextStyle(
                        fontSize: 12,
                        color: AppColors.onSurfaceVariant,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),

                // Inner label
                Positioned(
                  top: 150,
                  left: 10,
                  child: RotatedBox(
                    quarterTurns: 3,
                    child: Text(
                      'Inner',
                      style: TextStyle(
                        fontSize: 11,
                        color: AppColors.onSurfaceVariant,
                      ),
                    ),
                  ),
                ),

                // Outer label
                Positioned(
                  top: 150,
                  right: 10,
                  child: RotatedBox(
                    quarterTurns: 1,
                    child: Text(
                      'Outer',
                      style: TextStyle(
                        fontSize: 11,
                        color: AppColors.onSurfaceVariant,
                      ),
                    ),
                  ),
                ),

                _buildClickableSiteContainer(top: 50, left: 15, siteNumber: 9),
                _buildClickableSiteContainer(
                    top: 50, right: 15, siteNumber: 10),
                _buildClickableSiteContainer(
                    top: 110, left: 15, siteNumber: 11),
                _buildClickableSiteContainer(
                    top: 110, right: 15, siteNumber: 12),
                _buildClickableSiteContainer(
                    top: 170, left: 15, siteNumber: 13),
                _buildClickableSiteContainer(
                    top: 170, right: 15, siteNumber: 14),
                _buildClickableSiteContainer(
                    top: 230, left: 15, siteNumber: 15),
                _buildClickableSiteContainer(
                    top: 230, right: 15, siteNumber: 16),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // Fixed clickable site container
  Widget _buildClickableSiteContainer({
    double? top,
    double? bottom,
    double? left,
    double? right,
    required int siteNumber,
  }) {
    return Positioned(
      top: top,
      bottom: bottom,
      left: left,
      right: right,
      child: _buildSiteButton(siteNumber),
    );
  }

  Widget _buildSiteButton(int siteNumber) {
    // Check if this site is in the rotation
    final isInRotation = _sites.any((site) =>
        site.siteNumber == siteNumber && site.bodyArea == _selectedBodyArea);

    return GestureDetector(
      behavior: HitTestBehavior
          .opaque, // Ensures tap is registered even if transparent
      onTap: () {
        if (isInRotation) {
          // Find and remove this site
          final index = _sites.indexWhere((site) =>
              site.siteNumber == siteNumber &&
              site.bodyArea == _selectedBodyArea);
          if (index >= 0) {
            _removeSite(index);
          }
        } else {
          // Add this site
          _addSite(siteNumber);
        }
      },
      child: Container(
        width: 32, // Small circles
        height: 32,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: isInRotation ? AppColors.tertiary : AppColors.surface,
          border: Border.all(
            color: isInRotation ? AppColors.tertiary : AppColors.primary,
            width: 2,
          ),
        ),
        child: Center(
          child: Text(
            '$siteNumber',
            style: TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.bold,
              color: isInRotation ? AppColors.onTertiary : AppColors.primary,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSiteRotationSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Rotation Schedule', style: AppTextStyles.titleMedium),
            SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
            if (_sites.isEmpty)
              const Padding(
                padding: EdgeInsets.all(16),
                child: Text(
                  'No sites in rotation. Tap on numbered sites in the diagram above to add them to your rotation schedule.',
                  textAlign: TextAlign.center,
                ),
              )
            else ...[
              // Current site indicator
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppColors.tertiary.withAlpha(50),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: AppColors.tertiary),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.arrow_circle_right,
                      color: AppColors.tertiary,
                    ),
                    SharedWidgets.horizontalSpace(AppTheme.doubleSpacing),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Next Injection:',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: AppColors.tertiary,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'Site ${_sites[_currentSiteIndex].siteNumber} in ${_sites[_currentSiteIndex].bodyArea == InjectionBodyArea.abdomen ? 'Abdomen' : 'Thigh'}',
                            style: AppTextStyles.titleMedium,
                          ),
                        ],
                      ),
                    ),
                    IconButton(
                      icon: Icon(AppIcons.getIcon('redo')),
                      onPressed: () {
                        setState(() {
                          _currentSiteIndex =
                              (_currentSiteIndex + 1) % _sites.length;
                        });
                      },
                      tooltip: 'Advance to next site',
                    ),
                  ],
                ),
              ),

              SharedWidgets.verticalSpace(AppTheme.doubleSpacing),

              // List of all sites in rotation
              Text('All Sites in Rotation:', style: AppTextStyles.bodyMedium),
              SharedWidgets.verticalSpace(),

              for (int i = 0; i < _sites.length; i++)
                Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Row(
                    children: [
                      Container(
                        width: 32,
                        height: 32,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: i == _currentSiteIndex
                              ? AppColors.tertiary
                              : AppColors.surface,
                          border: Border.all(
                            color: i == _currentSiteIndex
                                ? AppColors.tertiary
                                : AppColors.primary,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '${_sites[i].siteNumber}',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: i == _currentSiteIndex
                                  ? AppColors.onTertiary
                                  : AppColors.primary,
                            ),
                          ),
                        ),
                      ),
                      SharedWidgets.horizontalSpace(AppTheme.doubleSpacing),
                      Text(
                        _getSiteDescription(_sites[i]),
                        style: TextStyle(
                          fontWeight: i == _currentSiteIndex
                              ? FontWeight.bold
                              : FontWeight.normal,
                        ),
                      ),
                      const Spacer(),
                      IconButton(
                        icon: Icon(
                          AppIcons.getIcon('remove_circle'),
                          color: AppColors.error,
                        ),
                        onPressed: () => _removeSite(i),
                      ),
                    ],
                  ),
                ),
            ],
            SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
            Center(
              child: ElevatedButton(
                onPressed: _saveRotation,
                child: const Text('Save Rotation'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _getSiteDescription(InjectionSite site) {
    if (site.bodyArea == InjectionBodyArea.abdomen) {
      final siteNum = site.siteNumber;

      // Upper Left Quadrant (Sites 1-4)
      if (siteNum == 1) return 'Upper Left Outer (Site $siteNum)';
      if (siteNum == 2) return 'Upper Left Inner (Site $siteNum)';
      if (siteNum == 3) return 'Upper-Mid Left Outer (Site $siteNum)';
      if (siteNum == 4) return 'Upper-Mid Left Inner (Site $siteNum)';

      // Upper Right Quadrant (Sites 5-8)
      if (siteNum == 5) return 'Upper Right Inner (Site $siteNum)';
      if (siteNum == 6) return 'Upper Right Outer (Site $siteNum)';
      if (siteNum == 7) return 'Upper-Mid Right Inner (Site $siteNum)';
      if (siteNum == 8) return 'Upper-Mid Right Outer (Site $siteNum)';

      // Lower Left Quadrant (Sites 9-12)
      if (siteNum == 9) return 'Lower-Mid Left Outer (Site $siteNum)';
      if (siteNum == 10) return 'Lower-Mid Left Inner (Site $siteNum)';
      if (siteNum == 11) return 'Lower Left Outer (Site $siteNum)';
      if (siteNum == 12) return 'Lower Left Inner (Site $siteNum)';

      // Lower Right Quadrant (Sites 13-16)
      if (siteNum == 13) return 'Lower-Mid Right Inner (Site $siteNum)';
      if (siteNum == 14) return 'Lower-Mid Right Outer (Site $siteNum)';
      if (siteNum == 15) return 'Lower Right Inner (Site $siteNum)';
      if (siteNum == 16) return 'Lower Right Outer (Site $siteNum)';

      return 'Abdomen (Site $siteNum)';
    } else {
      final siteNum = site.siteNumber;
      if (siteNum <= 8) {
        final position = siteNum <= 2
            ? 'Upper'
            : siteNum <= 4
                ? 'Middle Upper'
                : siteNum <= 6
                    ? 'Middle Lower'
                    : 'Lower';
        final side = siteNum % 2 == 1 ? 'Outer' : 'Inner';
        return 'Left Thigh - $position $side (Site $siteNum)';
      } else {
        final rightSiteNum = siteNum - 8;
        final position = rightSiteNum <= 2
            ? 'Upper'
            : rightSiteNum <= 4
                ? 'Middle Upper'
                : rightSiteNum <= 6
                    ? 'Middle Lower'
                    : 'Lower';
        final side = rightSiteNum % 2 == 1 ? 'Inner' : 'Outer';
        return 'Right Thigh - $position $side (Site $siteNum)';
      }
    }
  }
}

// Custom painter for abdomen guidelines
class AbdomenLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = AppTheme.grey.withAlpha(76)
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    // Horizontal dividing line
    canvas.drawLine(
      Offset(0, size.height / 2),
      Offset(size.width, size.height / 2),
      paint,
    );

    // Vertical dividing line
    canvas.drawLine(
      Offset(size.width / 2, 0),
      Offset(size.width / 2, size.height),
      paint,
    );
  }

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