import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class HarvestAnalysisScreen extends StatefulWidget {
  final String userId;

  const HarvestAnalysisScreen({Key? key, required this.userId}) : super(key: key);

  @override
  _HarvestAnalysisScreenState createState() => _HarvestAnalysisScreenState();
}

class _HarvestAnalysisScreenState extends State<HarvestAnalysisScreen> {
  bool _isLoading = true;
  List<Map<String, dynamic>> _harvestData = [];
  String _selectedPeriod = 'Tahun Ini';
  final List<String> _periods = ['Tahun Ini', '6 Bulan', '3 Bulan', '1 Bulan'];

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

  Future<void> _fetchHarvestData() async {
    if (widget.userId.isEmpty) {
      setState(() => _isLoading = false);
      return;
    }

    try {
      // Fetch harvest data from Supabase
      final response = await Supabase.instance.client
          .from('harvests')
          .select('*, crops(name, image_url)')
          .eq('user_id', widget.userId)
          .order('harvest_date', ascending: false);

      if (mounted) {
        setState(() {
          _harvestData = List<Map<String, dynamic>>.from(response);
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('Error fetching harvest data: $e');
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Analisis Panen',
                style: GoogleFonts.poppins(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
              IconButton(
                icon: const Icon(Icons.refresh),
                tooltip: 'Refresh Data',
                onPressed: () {
                  setState(() => _isLoading = true);
                  _fetchHarvestData().then((_) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('Data berhasil diperbarui')),
                    );
                  });
                },
              ),
            ],
          ),
          const SizedBox(height: 20),
          _buildPeriodSelector(),
          const SizedBox(height: 20),
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : _harvestData.isEmpty
                  ? _buildEmptyState()
                  : Expanded(
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            _buildSummaryCards(),
                            const SizedBox(height: 20),
                            _buildYieldChart(),
                            const SizedBox(height: 20),
                            _buildRecentHarvests(),
                          ],
                        ),
                      ),
                    ),
        ],
      ),
    );
  }

  Widget _buildPeriodSelector() {
    return Container(
      height: 40,
      decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        children: _periods.map((period) {
          final isSelected = period == _selectedPeriod;
          return Expanded(
            child: GestureDetector(
              onTap: () {
                setState(() => _selectedPeriod = period);
              },
              child: Container(
                decoration: BoxDecoration(
                  color: isSelected ? const Color(0xFF056839) : Colors.transparent,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Center(
                  child: Text(
                    period,
                    style: GoogleFonts.poppins(
                      color: isSelected ? Colors.white : Colors.grey[600],
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Expanded(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.analytics_outlined,
              size: 80,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              'Belum ada data panen',
              style: GoogleFonts.poppins(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Data analisis panen akan muncul setelah Anda menyelesaikan siklus tanam pertama',
              textAlign: TextAlign.center,
              style: GoogleFonts.poppins(
                fontSize: 14,
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSummaryCards() {
    // Calculate summary data
    double totalYield = 0;
    double totalRevenue = 0;
    int totalHarvests = _harvestData.length;

    for (var harvest in _harvestData) {
      totalYield += (harvest['yield_amount'] ?? 0).toDouble();
      totalRevenue += (harvest['revenue'] ?? 0).toDouble();
    }

    return Row(
      children: [
        _buildSummaryCard(
          title: 'Total Panen',
          value: '$totalHarvests',
          icon: Icons.inventory_2_outlined,
          color: Colors.blue,
        ),
        const SizedBox(width: 16),
        _buildSummaryCard(
          title: 'Total Hasil',
          value: '${totalYield.toStringAsFixed(1)} kg',
          icon: Icons.scale_outlined,
          color: Colors.green,
        ),
        const SizedBox(width: 16),
        _buildSummaryCard(
          title: 'Pendapatan',
          value: 'Rp ${totalRevenue.toStringAsFixed(0)}',
          icon: Icons.attach_money_outlined,
          color: Colors.orange,
        ),
      ],
    );
  }

  Widget _buildSummaryCard({
    required String title,
    required String value,
    required IconData icon,
    required Color color,
  }) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: 8),
            Text(
              value,
              style: GoogleFonts.poppins(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
              overflow: TextOverflow.ellipsis,
            ),
            Text(
              title,
              style: GoogleFonts.poppins(
                fontSize: 12,
                color: Colors.grey[600],
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildYieldChart() {
    return Container(
      height: 200,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Hasil Panen (kg)',
            style: GoogleFonts.poppins(
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: 16),
          Expanded(
            child: Center(
              child: Text(
                'Grafik hasil panen akan ditampilkan di sini',
                style: GoogleFonts.poppins(
                  fontSize: 14,
                  color: Colors.grey[500],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRecentHarvests() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Panen Terbaru',
          style: GoogleFonts.poppins(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
        const SizedBox(height: 12),
        ...(_harvestData.isEmpty
            ? [
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 10,
                        offset: const Offset(0, 5),
                      ),
                    ],
                  ),
                  child: Center(
                    child: Text(
                      'Belum ada data panen',
                      style: GoogleFonts.poppins(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    ),
                  ),
                )
              ]
            : _harvestData.take(5).map((harvest) {
                final cropName = harvest['crops']['name'] ?? 'Tanaman';
                final yieldAmount = harvest['yield_amount'] ?? 0;
                final revenue = harvest['revenue'] ?? 0;
                final harvestDate = DateTime.parse(harvest['harvest_date']);
                final now = DateTime.now();
                final difference = now.difference(harvestDate).inDays;
                
                String timeAgo;
                if (difference == 0) {
                  timeAgo = 'Hari ini';
                } else if (difference == 1) {
                  timeAgo = 'Kemarin';
                } else {
                  timeAgo = '$difference hari yang lalu';
                }

                return Container(
                  margin: const EdgeInsets.only(bottom: 12),
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 10,
                        offset: const Offset(0, 5),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      Container(
                        width: 50,
                        height: 50,
                        decoration: BoxDecoration(
                          color: Colors.green.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: const Center(
                          child: Icon(
                            Icons.eco,
                            color: Colors.green,
                          ),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              cropName,
                              style: GoogleFonts.poppins(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            Text(
                              '$yieldAmount kg - Rp $revenue',
                              style: GoogleFonts.poppins(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                      Text(
                        timeAgo,
                        style: GoogleFonts.poppins(
                          fontSize: 12,
                          color: Colors.grey[500],
                        ),
                      ),
                    ],
                  ),
                );
              }).toList()),
      ],
    );
  }
}
