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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NetCache Image Example',
      theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: true),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isPreloading = false;
  String _cacheSize = 'Calculating...';

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

  Future<void> _updateCacheSize() async {
    final size = await NetCacheImage.getCacheSize();
    setState(() {
      _cacheSize = '${(size / 1024 / 1024).toStringAsFixed(2)} MB';
    });
  }

  Future<void> _preloadImages() async {
    setState(() {
      _isPreloading = true;
    });

    try {
      await NetCacheImage.preload([
        'https://picsum.photos/300/200?random=1',
        'https://picsum.photos/300/200?random=2',
        'https://picsum.photos/300/200?random=3',
        'https://picsum.photos/300/200?random=4',
        'https://picsum.photos/300/200?random=5',
      ]);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Images preloaded successfully!')),
      );
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to preload images: $e')));
    } finally {
      setState(() {
        _isPreloading = false;
      });
      _updateCacheSize();
    }
  }

  Future<void> _clearCache() async {
    await NetCacheImage.clearCache();
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('Cache cleared!')));
    _updateCacheSize();
  }

  Future<void> _clearExpiredCache() async {
    await NetCacheImage.clearExpiredCache();
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('Expired cache cleared!')));
    _updateCacheSize();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('NetCache Image Example'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _updateCacheSize,
            tooltip: 'Refresh cache size',
          ),
        ],
      ),
      body: Column(
        children: [
          // Cache management section
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.grey[100],
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Cache Management',
                  style: Theme.of(context).textTheme.titleLarge,
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Text('Cache Size: $_cacheSize'),
                    const Spacer(),
                    ElevatedButton(
                      onPressed: _isPreloading ? null : _preloadImages,
                      child: _isPreloading
                          ? const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : const Text('Preload'),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    ElevatedButton(
                      onPressed: _clearCache,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red[100],
                      ),
                      child: const Text('Clear Cache'),
                    ),
                    const SizedBox(width: 8),
                    ElevatedButton(
                      onPressed: _clearExpiredCache,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange[100],
                      ),
                      child: const Text('Clear Expired'),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // Image examples
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(16),
              children: [
                _buildExampleSection(
                  'Basic Usage',
                  'Simple image loading with default settings',
                  'https://picsum.photos/300/200?random=10',
                ),
                const SizedBox(height: 16),
                _buildExampleSection(
                  'With Placeholder',
                  'Custom placeholder while loading',
                  'https://picsum.photos/300/200?random=11',
                  showPlaceholder: true,
                ),
                const SizedBox(height: 16),
                _buildExampleSection(
                  'With Error Widget',
                  'Custom error widget for failed loads',
                  'https://invalid-url-that-will-fail.com/image.jpg',
                  showErrorWidget: true,
                ),
                const SizedBox(height: 16),
                _buildExampleSection(
                  'Custom Configuration',
                  'With custom cache expiration and retry settings',
                  'https://picsum.photos/300/200?random=12',
                  customConfig: true,
                ),
                const SizedBox(height: 16),
                _buildGridExample(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildExampleSection(
    String title,
    String description,
    String imageUrl, {
    bool showPlaceholder = false,
    bool showErrorWidget = false,
    bool customConfig = false,
  }) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(height: 4),
            Text(description, style: Theme.of(context).textTheme.bodySmall),
            const SizedBox(height: 12),
            SizedBox(
              height: 200,
              child: NetCacheImage(
                url: imageUrl,
                placeholder: showPlaceholder
                    ? Container(
                        color: Colors.grey[300],
                        child: const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              CircularProgressIndicator(),
                              SizedBox(height: 8),
                              Text('Loading...'),
                            ],
                          ),
                        ),
                      )
                    : null,
                errorWidget: showErrorWidget
                    ? Container(
                        color: Colors.red[100],
                        child: const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.error, color: Colors.red, size: 48),
                              SizedBox(height: 8),
                              Text('Failed to load image'),
                            ],
                          ),
                        ),
                      )
                    : null,
                cacheExpiration: customConfig ? const Duration(days: 30) : null,
                maxRetries: customConfig ? 5 : 3,
                retryDelay: customConfig
                    ? const Duration(seconds: 1)
                    : const Duration(seconds: 2),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildGridExample() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Grid Example',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 4),
            Text(
              'Multiple images in a grid layout',
              style: Theme.of(context).textTheme.bodySmall,
            ),
            const SizedBox(height: 12),
            GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
                childAspectRatio: 1.5,
              ),
              itemCount: 6,
              itemBuilder: (context, index) {
                return NetCacheImage(
                  url: 'https://picsum.photos/200/150?random=${20 + index}',
                  placeholder: Container(
                    color: Colors.grey[300],
                    child: const Center(child: CircularProgressIndicator()),
                  ),
                  errorWidget: Container(
                    color: Colors.red[100],
                    child: const Center(
                      child: Icon(Icons.error, color: Colors.red),
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
