import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../../../../core/services/asset_service.dart';

const _staffAssetGreen = Color.fromARGB(255, 2, 105, 48);
const _staffAssetGold = Color.fromARGB(255, 204, 117, 4);
const _staffAssetInk = Color(0xFF1E2A24);
const _staffAssetMuted = Color(0xFF6E7973);
const _staffAssetBorder = Color(0xFFDDE5E0);

class AssignedAssetsTab extends StatefulWidget {
  const AssignedAssetsTab({super.key});

  @override
  State<AssignedAssetsTab> createState() => _AssignedAssetsTabState();
}

class _AssignedAssetsTabState extends State<AssignedAssetsTab> {
  bool _loading = true;
  String? _error;
  List<Map<String, dynamic>> _assets = const [];

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

  List<Map<String, dynamic>> _readRows(dynamic value) {
    if (value is! List) return [];
    return value
        .whereType<Map>()
        .map((row) => row.map((key, item) => MapEntry(key.toString(), item)))
        .toList();
  }

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final result = await AssetService.list();
      if (!mounted) return;
      setState(() {
        _assets = _readRows(result['data']);
        _loading = false;
      });
    } catch (error) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = AssetService.cleanError(error);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF3F6F4),
      body: CustomScrollView(slivers: [
        SliverAppBar(
          pinned: true,
          expandedHeight: 130,
          backgroundColor: Colors.white,
          surfaceTintColor: Colors.white,
          foregroundColor: _staffAssetInk,
          title: const Text('My assigned assets',
              style: TextStyle(fontWeight: FontWeight.w900)),
          actions: [
            IconButton(
              tooltip: 'Refresh assigned assets',
              onPressed: _loading ? null : _load,
              icon: const Icon(Icons.refresh_rounded, color: _staffAssetGreen),
            ),
            const SizedBox(width: 6),
          ],
          flexibleSpace: FlexibleSpaceBar(
            background: Stack(children: [
              const Positioned(
                top: 0, left: 0, right: 0,
                child: SizedBox(height: 4, child: ColoredBox(color: _staffAssetGold)),
              ),
              const Align(
                alignment: Alignment.bottomLeft,
                child: Padding(
                  padding: EdgeInsets.fromLTRB(20, 18, 20, 18),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('UNIVERSITY PROPERTY', style: TextStyle(
                          color: _staffAssetGreen, fontSize: 10,
                          fontWeight: FontWeight.w900, letterSpacing: 1.1)),
                      SizedBox(height: 5),
                      Text('Your current equipment and custody records',
                          style: TextStyle(color: _staffAssetInk, fontSize: 16,
                              fontWeight: FontWeight.w900)),
                    ],
                  ),
                ),
              ),
            ]),
          ),
        ),
        SliverToBoxAdapter(
          child: Container(
            margin: const EdgeInsets.fromLTRB(16, 14, 16, 12),
            padding: const EdgeInsets.all(18),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.zero,
              color: Colors.white,
              border: Border.all(color: _staffAssetBorder),
            ),
            child: Row(children: [
              Container(width: 46, height: 46,
                decoration: BoxDecoration(color: _staffAssetGreen.withOpacity(.09),
                    borderRadius: BorderRadius.zero),
                child: const Icon(Icons.inventory_2_outlined, color: _staffAssetGreen)),
              const SizedBox(width: 13),
              Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                Text('${_assets.length} ${_assets.length == 1 ? 'item' : 'items'} assigned',
                    style: const TextStyle(color: _staffAssetInk, fontSize: 16,
                        fontWeight: FontWeight.w900)),
                const SizedBox(height: 4),
                const Text('Review location, condition and return dates.',
                    style: TextStyle(color: _staffAssetMuted, fontSize: 10.5,
                        height: 1.5)),
              ])),
              const Icon(Icons.verified_user_outlined,
                  color: _staffAssetGold, size: 24),
            ]),
          ),
        ),
        if (_loading)
          const SliverFillRemaining(hasScrollBody: false,
              child: Center(child: CircularProgressIndicator(color: _staffAssetGreen)))
        else if (_error != null)
          SliverFillRemaining(hasScrollBody: false,
              child: _StaffAssetError(message: _error!, onRetry: _load))
        else if (_assets.isEmpty)
          const SliverFillRemaining(hasScrollBody: false,
              child: _NoAssignedAssets())
        else
          SliverToBoxAdapter(child: _StaffAssetGrid(assets: _assets)),
        const SliverToBoxAdapter(child: SizedBox(height: 24)),
      ]),
    );
  }

}

class _StaffAssetGrid extends StatelessWidget {
  final List<Map<String, dynamic>> assets;
  const _StaffAssetGrid({required this.assets});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      final columns = constraints.maxWidth >= 1200 ? 3 :
          (constraints.maxWidth >= 760 ? 2 : 1);
      final cardWidth = (constraints.maxWidth - 32 - (columns - 1) * 14) / columns;
      return Padding(
        padding: const EdgeInsets.fromLTRB(16, 5, 16, 20),
        child: Wrap(spacing: 14, runSpacing: 14,
          children: assets.map((asset) => SizedBox(
            width: cardWidth,
            child: _StaffAssetCard(asset: asset),
          )).toList()),
      );
    });
  }

}

class _StaffAssetCard extends StatelessWidget {
  final Map<String, dynamic> asset;
  const _StaffAssetCard({required this.asset});

  String _date(dynamic value) {
    if (value == null || '$value'.isEmpty) return 'Not set';
    try {
      return DateFormat('dd MMM yyyy').format(DateTime.parse('$value').toLocal());
    } catch (_) {
      return '$value';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.zero,
        border: Border.all(color: _staffAssetBorder),
        boxShadow: [
          BoxShadow(
              color: Colors.black.withOpacity(.025),
              blurRadius: 12,
              offset: const Offset(0, 5))
        ],
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          Container(
            width: 42,
            height: 42,
            decoration: BoxDecoration(
                color: _staffAssetGreen.withOpacity(.08),
                borderRadius: BorderRadius.zero),
            child: const Icon(Icons.devices_other_rounded,
                color: _staffAssetGreen),
          ),
          const SizedBox(width: 10),
          Expanded(
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                Text('${asset['asset_tag'] ?? ''}',
                    style: const TextStyle(
                        color: _staffAssetInk,
                        fontSize: 12,
                        fontWeight: FontWeight.w900)),
                const SizedBox(height: 3),
                Text('${asset['category'] ?? 'University asset'}',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                        color: _staffAssetMuted, fontSize: 10.5)),
              ])),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
            decoration: BoxDecoration(
                color: _staffAssetGreen.withOpacity(.09),
                borderRadius: BorderRadius.zero),
            child: const Text('ASSIGNED',
                style: TextStyle(
                    color: _staffAssetGreen,
                    fontSize: 8.5,
                    fontWeight: FontWeight.w900)),
          ),
        ]),
        const SizedBox(height: 14),
        Text('${asset['asset_name'] ?? ''}',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(
                color: _staffAssetInk,
                fontSize: 15,
                fontWeight: FontWeight.w900)),
        const SizedBox(height: 5),
        Text('${asset['campus'] ?? ''}',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(color: _staffAssetMuted, fontSize: 10.5)),
        const SizedBox(height: 12),
        _StaffAssetLine(
            label: 'Location',
            value: '${asset['location'] ?? 'Not recorded'}'.ifEmpty('Not recorded'),
            icon: Icons.place_outlined),
        const SizedBox(height: 8),
        _StaffAssetLine(
            label: 'Condition',
            value: '${asset['condition_status'] ?? 'Good'}',
            icon: Icons.health_and_safety_outlined),
        const SizedBox(height: 8),
        _StaffAssetLine(
            label: 'Assigned',
            value: _date(asset['assigned_at']),
            icon: Icons.event_available_outlined),
        const SizedBox(height: 8),
        _StaffAssetLine(
            label: 'Due back',
            value: _date(asset['due_back_date']),
            icon: Icons.event_busy_outlined),
        if ('${asset['assignment_note'] ?? ''}'.trim().isNotEmpty) ...[
          const SizedBox(height: 9),
          Text('${asset['assignment_note']}',
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                  color: _staffAssetMuted, fontSize: 10, height: 1.45)),
        ],
      ]),
    );
  }
}

class _StaffAssetLine extends StatelessWidget {
  final String label, value;
  final IconData icon;
  const _StaffAssetLine(
      {required this.label, required this.value, required this.icon});

  @override
  Widget build(BuildContext context) => Row(children: [
        Icon(icon, size: 14, color: _staffAssetMuted),
        const SizedBox(width: 6),
        SizedBox(
            width: 74,
            child: Text(label,
                style: const TextStyle(
                    color: _staffAssetMuted, fontSize: 10))),
        Expanded(
            child: Text(value,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                    color: _staffAssetInk,
                    fontSize: 10.5,
                    fontWeight: FontWeight.w700))),
      ]);
}

class _NoAssignedAssets extends StatelessWidget {
  const _NoAssignedAssets();
  @override
  Widget build(BuildContext context) => const Center(
        child: Padding(
          padding: EdgeInsets.all(26),
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            Icon(Icons.inventory_2_outlined,
                size: 56, color: Color(0xFF9AA79F)),
            SizedBox(height: 10),
            Text('No assets are currently assigned to you.',
                style: TextStyle(
                    color: _staffAssetInk, fontWeight: FontWeight.w800)),
            SizedBox(height: 5),
            Text('Contact your campus administrator if you expected an item here.',
                textAlign: TextAlign.center,
                style: TextStyle(color: _staffAssetMuted, fontSize: 11)),
          ]),
        ),
      );
}

class _StaffAssetError extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;
  const _StaffAssetError({required this.message, required this.onRetry});
  @override
  Widget build(BuildContext context) => Center(
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Text(message,
              textAlign: TextAlign.center,
              style: const TextStyle(color: _staffAssetMuted)),
          const SizedBox(height: 12),
          FilledButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('Try again'),
              style: FilledButton.styleFrom(backgroundColor: _staffAssetGreen)),
        ]),
      );
}

extension on String {
  String ifEmpty(String fallback) => trim().isEmpty ? fallback : this;
}
