import 'package:flutter/material.dart';
import 'package:barber_app/core/theme/app_theme.dart';
import 'package:barber_app/core/constants/app_strings.dart';
import 'package:barber_app/features/products/data/models/product_model.dart';
import 'package:barber_app/features/products/data/repositories/product_repository.dart';
import 'package:barber_app/shared/widgets/custom_text_field.dart';
import 'package:barber_app/shared/widgets/loading_button.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:barber_app/features/finances/data/repositories/transaction_repository.dart';

class AddProductPage extends StatefulWidget {
  final ProductModel? product;

  const AddProductPage({super.key, this.product});

  @override
  State<AddProductPage> createState() => _AddProductPageState();
}

class _AddProductPageState extends State<AddProductPage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _quantityController = TextEditingController();
  final _purchasePriceController = TextEditingController();
  final _salePriceController = TextEditingController();
  final _minStockController = TextEditingController();
  String _selectedCategory = ProductCategories.pastes;
  bool _isLoading = false;
  File? _imageFile;
  final _picker = ImagePicker();

  bool get _isEditing => widget.product != null;

  @override
  void initState() {
    super.initState();
    if (_isEditing) {
      _nameController.text = widget.product!.name;
      _quantityController.text = widget.product!.quantity.toString();
      _purchasePriceController.text = widget.product!.purchasePrice.toString();
      _salePriceController.text = widget.product!.salePrice.toString();
      _minStockController.text = widget.product!.minStock.toString();
      _selectedCategory = widget.product!.category;
      if (widget.product!.imagePath != null) {
        _imageFile = File(widget.product!.imagePath!);
      }
    } else {
      _minStockController.text = '5';
    }
  }

  bool _addTransaction = true;
  bool _isPaid = true;
  bool _isCustomCategory = false;
  final _customCategoryController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _quantityController.dispose();
    _purchasePriceController.dispose();
    _salePriceController.dispose();
    _minStockController.dispose();
    _customCategoryController.dispose();
    super.dispose();
  }

  Future<void> _pickImage(ImageSource source) async {
    try {
      final pickedFile = await _picker.pickImage(
        source: source,
        maxWidth: 1000,
        maxHeight: 1000,
        imageQuality: 85,
      );
      if (pickedFile != null) {
        setState(() {
          _imageFile = File(pickedFile.path);
        });
      }
    } catch (e) {
      debugPrint('Error picking image: $e');
    }
  }

  void _showImageSourceActionSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppColors.surface,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Icon(Icons.camera_alt, color: AppColors.primaryColor),
              title: const Text('Tirar Foto'),
              onTap: () {
                Navigator.pop(context);
                _pickImage(ImageSource.camera);
              },
            ),
            ListTile(
              leading: Icon(Icons.photo_library, color: AppColors.primaryColor),
              title: const Text('Escolher da Galeria'),
              onTap: () {
                Navigator.pop(context);
                _pickImage(ImageSource.gallery);
              },
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _saveProduct() async {
    if (!(_formKey.currentState?.validate() ?? false)) return;

    setState(() => _isLoading = true);

    try {
      final productRepo = ProductRepository();

      final category = _isCustomCategory
          ? _customCategoryController.text.trim().toLowerCase()
          : _selectedCategory;

      if (category.isEmpty) {
        throw Exception('Informe a categoria');
      }

      ProductModel? result;

      if (_isEditing) {
        final updated = widget.product!.copyWith(
          name: _nameController.text,
          category: category,
          quantity: int.parse(_quantityController.text),
          purchasePrice: double.parse(
            _purchasePriceController.text.replaceAll(',', '.'),
          ),
          salePrice: double.parse(
            _salePriceController.text.replaceAll(',', '.'),
          ),
          minStock: int.parse(_minStockController.text),
          imagePath: _imageFile?.path,
        );
        await productRepo.updateProduct(updated);
        result = updated;
      } else {
        result = await productRepo.createProduct(
          name: _nameController.text,
          category: category,
          quantity: int.parse(_quantityController.text),
          purchasePrice: double.parse(
            _purchasePriceController.text.replaceAll(',', '.'),
          ),
          salePrice: double.parse(
            _salePriceController.text.replaceAll(',', '.'),
          ),
          minStock: int.parse(_minStockController.text),
          imagePath: _imageFile?.path,
        );
      }

      if (result == null) throw Exception('Falha ao salvar produto');
      final savedProduct = result;

      // Adicionar Transação Financeira (Despesa)
      if (!_isEditing && _addTransaction) {
        final totalCost = savedProduct.purchasePrice * savedProduct.quantity;
        if (totalCost > 0) {
          final transactionRepo = TransactionRepository();
          await transactionRepo.createExpense(
            amount: totalCost,
            description:
                'Compra de Estoque: ${savedProduct.name} (${savedProduct.quantity} un)',
            dueDate: DateTime.now(),
            isPaid: _isPaid,
          );
        }
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text(AppStrings.savedSuccessfully),
            backgroundColor: AppColors.success,
          ),
        );
        Navigator.pop(context);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erro: $e'), backgroundColor: AppColors.error),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditing ? 'Editar Produto' : AppStrings.newProduct),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Upload de Foto
                Center(
                  child: GestureDetector(
                    onTap: () => _showImageSourceActionSheet(context),
                    child: Container(
                      width: 120,
                      height: 120,
                      decoration: BoxDecoration(
                        color: AppColors.surfaceLight,
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                          color: AppColors.primaryColor.withValues(alpha: 0.3),
                          width: 2,
                        ),
                        image: _imageFile != null
                            ? DecorationImage(
                                image: FileImage(_imageFile!),
                                fit: BoxFit.cover,
                              )
                            : null,
                      ),
                      child: _imageFile == null
                          ? Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.add_a_photo_outlined,
                                  color: AppColors.primaryColor,
                                  size: 40,
                                ),
                                const SizedBox(height: 8),
                                const Text(
                                  'Foto',
                                  style: TextStyle(
                                    color: AppColors.textSecondary,
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            )
                          : Stack(
                              children: [
                                Positioned(
                                  right: -10,
                                  top: -10,
                                  child: IconButton(
                                    icon: const Icon(
                                      Icons.cancel,
                                      color: AppColors.error,
                                    ),
                                    onPressed: () =>
                                        setState(() => _imageFile = null),
                                  ),
                                ),
                              ],
                            ),
                    ),
                  ),
                ),
                const SizedBox(height: 32),

                CustomTextField(
                  controller: _nameController,
                  label: AppStrings.productName,
                  hint: 'Nome do produto',
                  prefixIcon: Icons.inventory_2_outlined,
                  validator: (v) =>
                      v?.isEmpty ?? true ? 'Informe o nome' : null,
                ),
                const SizedBox(height: 20),

                // Categoria
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      AppStrings.category,
                      style: TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        setState(() {
                          _isCustomCategory = !_isCustomCategory;
                          if (!_isCustomCategory) {
                            _selectedCategory = ProductCategories.pastes;
                          }
                        });
                      },
                      child: Text(
                        _isCustomCategory
                            ? 'Selecionar Lista'
                            : 'Nova Categoria',
                        style: TextStyle(fontSize: 12),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),

                if (_isCustomCategory)
                  CustomTextField(
                    controller: _customCategoryController,
                    label: 'Nome da Categoria',
                    hint: 'Ex: Eletrônicos',
                    prefixIcon: Icons.category_outlined,
                  )
                else
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    decoration: BoxDecoration(
                      color: AppColors.surfaceLight,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton<String>(
                        isExpanded: true,
                        value: ProductCategories.all.contains(_selectedCategory)
                            ? _selectedCategory
                            : null,
                        hint: Text(_selectedCategory),
                        dropdownColor: AppColors.surface,
                        items: ProductCategories.all.map((cat) {
                          return DropdownMenuItem(
                            value: cat,
                            child: Text(ProductCategories.getDisplayName(cat)),
                          );
                        }).toList(),
                        onChanged: (value) {
                          if (value != null)
                            setState(() => _selectedCategory = value);
                        },
                      ),
                    ),
                  ),
                const SizedBox(height: 20),

                CustomTextField(
                  controller: _quantityController,
                  label: AppStrings.quantity,
                  hint: '0',
                  prefixIcon: Icons.numbers,
                  keyboardType: TextInputType.number,
                  validator: (v) =>
                      v?.isEmpty ?? true ? 'Informe a quantidade' : null,
                ),
                const SizedBox(height: 20),

                Row(
                  children: [
                    Expanded(
                      child: CustomTextField(
                        controller: _purchasePriceController,
                        label: AppStrings.purchasePrice,
                        hint: '0,00',
                        prefixIcon: Icons.attach_money,
                        keyboardType: TextInputType.number,
                        validator: (v) => v?.isEmpty ?? true ? 'Informe' : null,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: CustomTextField(
                        controller: _salePriceController,
                        label: AppStrings.salePrice,
                        hint: '0,00',
                        prefixIcon: Icons.attach_money,
                        keyboardType: TextInputType.number,
                        validator: (v) => v?.isEmpty ?? true ? 'Informe' : null,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),

                CustomTextField(
                  controller: _minStockController,
                  label: AppStrings.minStock,
                  hint: '5',
                  prefixIcon: Icons.warning_amber_outlined,
                  keyboardType: TextInputType.number,
                  validator: (v) => v?.isEmpty ?? true ? 'Informe' : null,
                ),

                const SizedBox(height: 24),
                const Divider(color: AppColors.surfaceLight),
                const SizedBox(height: 16),

                // Integração com Financeiro
                if (!_isEditing) ...[
                  SwitchListTile(
                    title: const Text(
                      'Lançar despesa no financeiro?',
                      style: TextStyle(color: AppColors.textPrimary),
                    ),
                    subtitle: const Text(
                      'Cria uma conta a pagar/paga referente a esta compra',
                      style: TextStyle(
                        color: AppColors.textSecondary,
                        fontSize: 12,
                      ),
                    ),
                    value: _addTransaction,
                    activeThumbColor: AppColors.primaryColor,
                    onChanged: (val) => setState(() => _addTransaction = val),
                  ),

                  if (_addTransaction)
                    CheckboxListTile(
                      title: const Text(
                        'Já foi pago?',
                        style: TextStyle(color: AppColors.textPrimary),
                      ),
                      value: _isPaid,
                      activeColor: AppColors.success,
                      checkColor: Colors.white,
                      onChanged: (val) =>
                          setState(() => _isPaid = val ?? false),
                      controlAffinity: ListTileControlAffinity.leading,
                    ),
                ],

                const SizedBox(height: 32),

                LoadingButton(
                  text: AppStrings.save,
                  isLoading: _isLoading,
                  onPressed: _saveProduct,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
