import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../../core/api/api_error_mapper.dart';
import '../../../core/l10n/l10n.dart';
import '../../../core/ui/async_state_views.dart';
import '../../auth/data/auth_providers.dart';
import '../data/inventory_providers.dart';

class InventoryDetailScreen extends ConsumerWidget {
  final int itemId;

  const InventoryDetailScreen({super.key, required this.itemId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final itemAsync = ref.watch(inventoryDetailProvider(itemId));

    return Scaffold(
      appBar: AppBar(
        title: itemAsync.maybeWhen(
          data: (item) => Text(item.productName),
          orElse: () => Text(context.l10n.inventoryTitle),
        ),
        actions: [
          if (itemAsync.hasValue) ...[
            IconButton(
              tooltip: context.l10n.editTooltip,
              icon: const Icon(Icons.edit_outlined),
              onPressed: () => context.push('/inventory/$itemId/edit'),
            ),
            _DeleteButton(itemId: itemId),
          ],
        ],
      ),
      body: itemAsync.when(
        loading: () => LoadingStateView(label: context.l10n.loadingLabel),
        error: (e, _) => ErrorStateView(
          message: mapErrorToUserMessage(e, context),
          onRetry: () => ref.invalidate(inventoryDetailProvider(itemId)),
        ),
        data: (item) => ListView(
          padding: const EdgeInsets.all(16),
          children: [
            _InfoRow(label: context.l10n.inventoryProductLabel, value: item.productName),
            _InfoRow(
              label: context.l10n.inventoryQuantityDisplayLabel,
              value: '${item.quantity} ${item.unit}',
            ),
            if (item.location != null && item.location!.isNotEmpty)
              _InfoRow(label: context.l10n.inventoryLocationDisplayLabel, value: item.location!),
            if (item.brand != null && item.brand!.isNotEmpty)
              _InfoRow(label: context.l10n.inventoryBrandDisplayLabel, value: item.brand!),
            if (item.purchaseDate != null)
              _InfoRow(label: context.l10n.inventoryPurchaseDateLabel, value: _formatDate(item.purchaseDate!)),
            if (item.bestBeforeDate != null)
              _InfoRow(label: context.l10n.inventoryBestBeforeLabel, value: _formatDate(item.bestBeforeDate!)),
            _InfoRow(label: context.l10n.openedLabel, value: item.opened ? context.l10n.yesLabel : context.l10n.noLabel),
            if (item.comment != null && item.comment!.isNotEmpty)
              _InfoRow(label: context.l10n.commentLabel, value: item.comment!),
            const SizedBox(height: 24),
            OutlinedButton.icon(
              onPressed: () => context.push('/inventory/$itemId/consume'),
              icon: const Icon(Icons.remove_circle_outline),
              label: Text(context.l10n.inventoryConsumeAction),
            ),
            const SizedBox(height: 8),
            TextButton.icon(
              onPressed: () => context.push('/inventory/$itemId/history'),
              icon: const Icon(Icons.history),
              label: Text(context.l10n.inventoryHistoryAction),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDate(String iso) {
    try {
      final dt = DateTime.parse(iso);
      return '${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}';
    } catch (_) {
      return iso;
    }
  }
}

class _DeleteButton extends ConsumerWidget {
  final int itemId;

  const _DeleteButton({required this.itemId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return IconButton(
      tooltip: context.l10n.deleteTooltip,
      icon: const Icon(Icons.delete_outline),
      onPressed: () async {
        final confirmed = await showDialog<bool>(
          context: context,
          builder: (ctx) => AlertDialog(
            title: Text(context.l10n.inventoryDeleteTitle),
            content: Text(context.l10n.cannotBeUndone),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(ctx, false),
                child: Text(context.l10n.cancelAction),
              ),
              FilledButton(
                onPressed: () => Navigator.pop(ctx, true),
                child: Text(context.l10n.deleteAction),
              ),
            ],
          ),
        );

        if (confirmed != true || !context.mounted) return;

        try {
          final token = await ref.read(authStateProvider.future);
          await ref
              .read(inventoryRepositoryProvider)
              .deleteInventoryItem(itemId, token: token);
          ref.invalidate(inventoryProvider);
          if (context.mounted) context.go('/inventory');
        } catch (e) {
          if (context.mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(mapErrorToUserMessage(e, context))),
            );
          }
        }
      },
    );
  }
}

class _InfoRow extends StatelessWidget {
  final String label;
  final String value;

  const _InfoRow({required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 120,
            child: Text(
              label,
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
            ),
          ),
          Expanded(child: Text(value)),
        ],
      ),
    );
  }
}
