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

import '../models/tax_setting_model.dart';
import '../services/tax_setting_repository.dart';

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

  @override
  State<TaxSettingScreen> createState() => _TaxSettingScreenState();
}

class _TaxSettingScreenState extends State<TaxSettingScreen> {
  final TaxSettingRepository _repository = TaxSettingRepository();
  final TextEditingController _rateController = TextEditingController();
  String _roundingMode = 'round';
  bool _isLoading = true;

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

  Future<void> _load() async {
    setState(() => _isLoading = true);
    final setting = await _repository.fetchCurrentSetting();
    if (!mounted) return;
    setState(() {
      _rateController.text = (setting.rate * 100).toStringAsFixed(1);
      _roundingMode = setting.roundingMode;
      _isLoading = false;
    });
  }

  Future<void> _save() async {
    final ratePercent = double.tryParse(_rateController.text);
    if (ratePercent == null) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('税込率は数値で入力してください')));
      return;
    }
    final setting = TaxSetting(
      id: const Uuid().v4(),
      rate: ratePercent / 100,
      roundingMode: _roundingMode,
      updatedAt: DateTime.now(),
    );
    await _repository.saveSetting(setting);
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('税設定を保存しました')));
    _load();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: const BackButton(),
        title: const Text('M7:消費税・端数設定'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextField(
                    controller: _rateController,
                    decoration: const InputDecoration(labelText: '税率 (%)', suffixText: '%'),
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                  ),
                  const SizedBox(height: 16),
                  DropdownButtonFormField<String>(
                    initialValue: _roundingMode,
                    decoration: const InputDecoration(labelText: '端数処理'),
                    items: const [
                      DropdownMenuItem(value: 'round', child: Text('四捨五入')),
                      DropdownMenuItem(value: 'ceil', child: Text('切り上げ')),
                      DropdownMenuItem(value: 'floor', child: Text('切り捨て')),
                    ],
                    onChanged: (value) => setState(() => _roundingMode = value ?? 'round'),
                  ),
                  const Spacer(),
                  SizedBox(
                    width: double.infinity,
                    child: FilledButton.icon(
                      icon: const Icon(Icons.save),
                      onPressed: _save,
                      label: const Text('保存'),
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}
