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

import '../../../core/utils/global_error_handler.dart';
import '../../../core/l10n/l10n.dart';
import '../../auth/data/auth_providers.dart';
import '../data/import_providers.dart';

/// Accepted MIME types / extensions for recipe file import.
const _allowedExtensions = ['pdf', 'png', 'jpg', 'jpeg', 'webp', 'bmp'];

/// Tab for importing a recipe via file upload or URL.
///
/// On success navigates to `/recipes/create` with the parsed markdown
/// passed as GoRouter `extra`.
class RecipeImportTab extends ConsumerStatefulWidget {
  const RecipeImportTab({super.key});

  @override
  ConsumerState<RecipeImportTab> createState() => _RecipeImportTabState();
}

class _RecipeImportTabState extends ConsumerState<RecipeImportTab> {
  bool _isLoading = false;
  PlatformFile? _pickedFile;
  _Method _method = _Method.file;
  final _urlCtrl = TextEditingController();

  @override
  void initState() {
    super.initState();
    _urlCtrl.addListener(() => setState(() {}));
  }

  @override
  void dispose() {
    _urlCtrl.dispose();
    super.dispose();
  }

  // ── File picker ──────────────────────────────────────────────────────────

  Future<void> _pickFile() async {
    final result = await FilePicker.pickFiles(
      type: FileType.custom,
      allowedExtensions: _allowedExtensions,
      withData: true, // needed on Flutter web to get bytes
    );
    if (result == null || result.files.isEmpty) return;
    setState(() {
      _pickedFile = result.files.first;
    });
  }

  // ── Import ────────────────────────────────────────────────────────────

  Future<void> _submit() async {
    if (_pickedFile == null && _method == _Method.file) {
      showGlobalErrorDialog(context, 'Vänligen välj en fil först');
      return;
    }

    setState(() => _isLoading = true);

    try {
      final token = ref.read(authStateProvider).maybeWhen(
        data: (t) => t,
        orElse: () => null,
          ) ??
          await ref.read(authStateProvider.future);
      final repo = ref.read(importRepositoryProvider);
      final result = _method == _Method.file
          ? await repo.importFile(
              bytes: _pickedFile!.bytes!,
              filename: _pickedFile!.name,
              token: token,
            )
          : await repo.importUrl(
              url: _urlCtrl.text,
              token: token,
            );

      if (!mounted) return;
      context.push('/recipes/create', extra: {
        'markdown': result.markdown,
        'imageUrl': result.imageUrl,
      });
    } catch (e) {
      showGlobalErrorDialog(context, 'Ett fel uppstod vid import: $e');
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  bool get _canSubmit {
    if (_isLoading) return false;
    if (_method == _Method.file) return _pickedFile?.bytes != null;
    return _urlCtrl.text.trim().isNotEmpty;
  }

  // ── Build ────────────────────────────────────────────────────────────────

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            context.l10n.importTabDescription,
            style: theme.textTheme.bodyMedium
                ?.copyWith(color: theme.colorScheme.onSurfaceVariant),
          ),
          const SizedBox(height: 20),

          // ── Metodväljare ────────────────────────────────────────────────
          SegmentedButton<_Method>(
            segments: [
              ButtonSegment(
                value: _Method.file,
                label: Text(context.l10n.importFileTabLabel),
                icon: const Icon(Icons.upload_file_outlined),
              ),
              ButtonSegment(
                value: _Method.url,
                label: Text(context.l10n.importLinkTabLabel),
                icon: const Icon(Icons.link),
              ),
            ],
            selected: {_method},
            onSelectionChanged: (s) =>
                setState(() => _method = s.first),
          ),
          const SizedBox(height: 24),

          // ── Filläge ─────────────────────────────────────────────────────
          if (_method == _Method.file) ...[
            OutlinedButton.icon(
              onPressed: _isLoading ? null : _pickFile,
              icon: const Icon(Icons.attach_file),
              label: Text(
                _pickedFile == null
                    ? context.l10n.importChooseFileAction
                    : _pickedFile!.name,
              ),
            ),
            if (_pickedFile != null) ...[
              const SizedBox(height: 8),
              Text(
                '${(_pickedFile!.size / 1024).round()} KB',
                style: theme.textTheme.bodySmall
                    ?.copyWith(color: theme.colorScheme.outline),
              ),
            ],
          ],

          // ── URL-läge ────────────────────────────────────────────────────
          if (_method == _Method.url) ...[
            TextField(
              controller: _urlCtrl,
              keyboardType: TextInputType.url,
              autofocus: true,
              enabled: !_isLoading,
              decoration: InputDecoration(
                labelText: context.l10n.importLinkLabel,
                hintText: context.l10n.importLinkHint,
                prefixIcon: const Icon(Icons.link),
                border: const OutlineInputBorder(),
              ),
              onSubmitted: (_) {
                if (_canSubmit) _submit();
              },
            ),
          ],

          const SizedBox(height: 24),

          // ── Laddningsindikator ───────────────────────────────────────────
          if (_isLoading) ...[
            const LinearProgressIndicator(),
            const SizedBox(height: 8),
            Text(
              context.l10n.importFileProcessing,
              style: theme.textTheme.bodySmall
                  ?.copyWith(color: theme.colorScheme.onSurfaceVariant),
            ),
            const SizedBox(height: 16),
          ],


          // ── Knapp ───────────────────────────────────────────────────────
          FilledButton.icon(
            onPressed: _canSubmit ? _submit : null,
            icon: const Icon(Icons.auto_awesome_outlined),
            label: Text(_method == _Method.file
                ? context.l10n.importFileAction
                : context.l10n.importLinkAction),
          ),

          const SizedBox(height: 24),
          const Divider(),
          const SizedBox(height: 12),

          // ── Alternativ ──────────────────────────────────────────────────
          TextButton.icon(
            onPressed: () => context.push('/recipes/create'),
            icon: const Icon(Icons.edit_outlined),
            label: Text(context.l10n.importWriteInstead),
          ),
        ],
      ),
    );
  }
}

enum _Method { file, url }
