import 'package:flutter/material.dart';
import 'package:xp_models/xp_models.dart';
import '../theme/app_theme.dart';

class ClassificationCard extends StatefulWidget {
  final List<ApplicationClassification> classifications;
  final List<UnclassifiedApplication> unclassified;
  final Future<void> Function(String, String) onSaveClassification;
  final Future<void> Function(String) onDeleteClassification;

  const ClassificationCard({
    super.key,
    required this.classifications,
    required this.unclassified,
    required this.onSaveClassification,
    required this.onDeleteClassification,
  });

  @override
  State<ClassificationCard> createState() => _ClassificationCardState();
}

class _ClassificationCardState extends State<ClassificationCard> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

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

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.category, color: AppTheme.primaryColor),
                const SizedBox(width: 8),
                Text(
                  'App Classifications',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
                ),
              ],
            ),
            const SizedBox(height: 16),
            TabBar(
              controller: _tabController,
              labelColor: AppTheme.primaryColor,
              unselectedLabelColor: Colors.grey,
              indicatorColor: AppTheme.primaryColor,
              tabs: [
                Tab(text: 'Classified (${widget.classifications.length})'),
                Tab(text: 'Unclassified (${widget.unclassified.length})'),
              ],
            ),
            const SizedBox(height: 16),
            SizedBox(
              height: 400,
              child: TabBarView(controller: _tabController, children: [_buildClassifiedTab(), _buildUnclassifiedTab()]),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildClassifiedTab() {
    if (widget.classifications.isEmpty) {
      return const Center(child: Text('No classified applications yet'));
    }

    return ListView.builder(
      itemCount: widget.classifications.length,
      itemBuilder: (context, index) {
        final classification = widget.classifications[index];
        return _ClassifiedItem(classification: classification, onDelete: widget.onDeleteClassification);
      },
    );
  }

  Widget _buildUnclassifiedTab() {
    if (widget.unclassified.isEmpty) {
      return const Center(child: Text('No unclassified applications'));
    }

    return ListView.builder(
      itemCount: widget.unclassified.length,
      itemBuilder: (context, index) {
        final app = widget.unclassified[index];
        return _UnclassifiedItem(app: app, onClassify: widget.onSaveClassification);
      },
    );
  }
}

class _ClassifiedItem extends StatelessWidget {
  final ApplicationClassification classification;
  final Future<void> Function(String) onDelete;

  const _ClassifiedItem({required this.classification, required this.onDelete});

  @override
  Widget build(BuildContext context) {
    final categoryIcon = _getCategoryIcon(classification.categoryId);
    final categoryName = _formatCategoryName(classification.categoryId);

    return Card(
      margin: const EdgeInsets.symmetric(vertical: 4),
      child: ListTile(
        leading: Text(categoryIcon, style: const TextStyle(fontSize: 20)),
        title: Text(classification.applicationName),
        subtitle: Text(categoryName),
        trailing: IconButton(
          icon: const Icon(Icons.delete, color: AppTheme.errorColor),
          onPressed: () => _showDeleteDialog(context),
        ),
      ),
    );
  }

  void _showDeleteDialog(BuildContext context) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('Delete Classification'),
            content: Text('Are you sure you want to remove the classification for ${classification.applicationName}?'),
            actions: [
              TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel')),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  onDelete(classification.applicationName);
                },
                child: const Text('Delete'),
              ),
            ],
          ),
    );
  }

  String _getCategoryIcon(String categoryId) {
    const icons = {
      'coding': '💻',
      'focused_browsing': '🔍',
      'collaboration': '🤝',
      'meetings': '📅',
      'misc': '📝',
      'uncategorized': '❓',
    };
    return icons[categoryId] ?? '📊';
  }

  String _formatCategoryName(String categoryId) {
    const names = {
      'coding': 'Coding',
      'focused_browsing': 'Focused Browsing',
      'collaboration': 'Collaboration',
      'meetings': 'Meetings',
      'misc': 'Miscellaneous',
      'uncategorized': 'Uncategorized',
    };
    return names[categoryId] ?? categoryId;
  }
}

class _UnclassifiedItem extends StatefulWidget {
  final UnclassifiedApplication app;
  final Future<void> Function(String, String) onClassify;

  const _UnclassifiedItem({required this.app, required this.onClassify});

  @override
  State<_UnclassifiedItem> createState() => _UnclassifiedItemState();
}

class _UnclassifiedItemState extends State<_UnclassifiedItem> {
  String? _selectedCategory;
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    final lastSeen = widget.app.lastSeen;

    return Card(
      margin: const EdgeInsets.symmetric(vertical: 4),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.app.applicationName,
                        style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
                      ),
                      Text(
                        '${widget.app.occurrenceCount} times • Last: ${_formatDate(lastSeen)}',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: DropdownButtonFormField<String>(
                    value: _selectedCategory,
                    decoration: const InputDecoration(
                      labelText: 'Select category',
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    ),
                    items: const [
                      DropdownMenuItem(value: 'coding', child: Text('💻 Coding')),
                      DropdownMenuItem(value: 'focused_browsing', child: Text('🔍 Focused Browsing')),
                      DropdownMenuItem(value: 'collaboration', child: Text('🤝 Collaboration')),
                      DropdownMenuItem(value: 'meetings', child: Text('📅 Meetings')),
                      DropdownMenuItem(value: 'misc', child: Text('📝 Miscellaneous')),
                      DropdownMenuItem(value: 'uncategorized', child: Text('❓ Uncategorized')),
                    ],
                    onChanged: (value) {
                      setState(() {
                        _selectedCategory = value;
                      });
                    },
                  ),
                ),
                const SizedBox(width: 12),
                ElevatedButton(
                  onPressed: _selectedCategory == null || _isLoading ? null : _classifyApp,
                  child:
                      _isLoading
                          ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
                          : const Text('Classify'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _classifyApp() async {
    if (_selectedCategory == null) return;

    setState(() {
      _isLoading = true;
    });

    try {
      await widget.onClassify(widget.app.applicationName, _selectedCategory!);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('${widget.app.applicationName} classified successfully'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Failed to classify: $e'), backgroundColor: AppTheme.errorColor));
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  String _formatDate(DateTime date) {
    return '${date.month}/${date.day}/${date.year}';
  }
}
