import 'package:flutter/material.dart';
import '../core/models.dart';
import '../core/report_generator.dart';
import '../data/cities.dart';
import '../l10n/l10n.dart';
import 'report_screen.dart';
import 'theme.dart';
class InputScreen extends StatefulWidget {
  const InputScreen({super.key});

  @override
  State<InputScreen> createState() => _InputScreenState();
}

class _InputScreenState extends State<InputScreen> {
  final _name = TextEditingController(text: '');
  final _lon = TextEditingController(text: '116.4074');
  final _lat = TextEditingController(text: '39.9042');
  DateTime _dt = DateTime(1973, 10, 15, 12, 0);
  Gender _gender = Gender.male;
  CityLocation? _city = majorCities.first;

  @override
  void dispose() {
    _name.dispose();
    _lon.dispose();
    _lat.dispose();
    super.dispose();
  }

  Future<void> _pickDateTime() async {
    final d = await showDatePicker(
      context: context,
      initialDate: _dt,
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
    );
    if (d == null || !mounted) return;
    final t = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.fromDateTime(_dt),
    );
    if (t == null || !mounted) return;
    setState(() {
      _dt = DateTime(d.year, d.month, d.day, t.hour, t.minute);
    });
  }

  void _submit() {
    final lon = double.tryParse(_lon.text) ?? 116.4;
    final lat = double.tryParse(_lat.text) ?? 39.9;
    final input = BirthInput(
      name: _name.text.trim().isEmpty ? 'Seeker' : _name.text.trim(),
      localDateTime: _dt,
      longitude: lon,
      latitude: lat,
      gender: _gender,
      placeName: _city?.name ?? 'Custom',
    );
    final report = ReportGenerator.generate(input);
    Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => ReportScreen(report: report)),
    );
  }

  @override
  Widget build(BuildContext context) {
    final l = LangScope.of(context).l10n;
    return Scaffold(
      appBar: AppBar(title: Text(l('newAnalysis'))),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          TextField(
            controller: _name,
            decoration: InputDecoration(labelText: l('name')),
          ),
          const SizedBox(height: 16),
          Text(l('gender'), style: const TextStyle(fontWeight: FontWeight.w600)),
          const SizedBox(height: 8),
          SegmentedButton<Gender>(
            segments: [
              ButtonSegment(value: Gender.male, label: Text(l('male'))),
              ButtonSegment(value: Gender.female, label: Text(l('female'))),
            ],
            selected: {_gender},
            onSelectionChanged: (s) => setState(() => _gender = s.first),
          ),
          const SizedBox(height: 16),
          ListTile(
            contentPadding: EdgeInsets.zero,
            title: Text(l('birthTime')),
            subtitle: Text(_dt.toString().substring(0, 16)),
            trailing: const Icon(Icons.schedule),
            onTap: _pickDateTime,
          ),
          const SizedBox(height: 8),
          DropdownButtonFormField<CityLocation>(
            value: _city,
            decoration: InputDecoration(labelText: l('place')),
            items: majorCities
                .map(
                  (c) => DropdownMenuItem(
                    value: c,
                    child: Text(l.cityName(c.name, c.nameZh, c.nameJa)),
                  ),
                )
                .toList(),
            onChanged: (c) {
              if (c == null) return;
              setState(() {
                _city = c;
                _lon.text = c.longitude.toStringAsFixed(4);
                _lat.text = c.latitude.toStringAsFixed(4);
              });
            },
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _lon,
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true, signed: true),
                  decoration: InputDecoration(labelText: l('longitude')),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: TextField(
                  controller: _lat,
                  keyboardType:
                      const TextInputType.numberWithOptions(decimal: true, signed: true),
                  decoration: InputDecoration(labelText: l('latitude')),
                ),
              ),
            ],
          ),
          const SizedBox(height: 28),
          ElevatedButton(
            onPressed: _submit,
            child: Text(l('generate')),
          ),
          const SizedBox(height: 12),
          Text(
            l('copyright'),
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 11, color: AppTheme.ink.withValues(alpha: 0.45)),
          ),
        ],
      ),
    );
  }
}
