part of '../../app/app.dart';

class PewarnaanLangsungExpertiseWizard extends StatefulWidget {
  const PewarnaanLangsungExpertiseWizard({
    super.key,
    required this.item,
    required this.user,
    required this.staffOptions,
    required this.optionSets,
    required this.textControllers,
    required this.selectValues,
    required this.multiValues,
    required this.staffValues,
    required this.criticalValue,
    required this.isSupervisor,
    required this.saving,
    required this.onCriticalChanged,
    required this.onChanged,
    required this.onSave,
    required this.initialStep,
    required this.onStepChanged,
  });

  final Map<String, dynamic> item;
  final Map<String, dynamic> user;
  final Map<String, dynamic> staffOptions;
  final Map<String, dynamic> optionSets;
  final Map<String, TextEditingController> textControllers;
  final Map<String, String> selectValues;
  final Map<String, Set<String>> multiValues;
  final Map<String, String> staffValues;
  final bool criticalValue;
  final bool isSupervisor;
  final bool saving;
  final ValueChanged<bool> onCriticalChanged;
  final VoidCallback onChanged;
  final ValueChanged<String> onSave;
  final int initialStep;
  final ValueChanged<int> onStepChanged;

  @override
  State<PewarnaanLangsungExpertiseWizard> createState() =>
      _PewarnaanLangsungExpertiseWizardState();
}

class _PewarnaanLangsungExpertiseWizardState
    extends State<PewarnaanLangsungExpertiseWizard> {
  late int _step;

  @override
  void initState() {
    super.initState();
    _step = widget.initialStep.clamp(0, 4);
  }

  @override
  void didUpdateWidget(covariant PewarnaanLangsungExpertiseWizard oldWidget) {
    super.didUpdateWidget(oldWidget);
    final nextStep = widget.initialStep.clamp(0, 4);
    if (nextStep != _step) {
      _step = nextStep;
    }
  }

  void _setStep(int step) {
    final nextStep = step.clamp(0, 4);
    setState(() => _step = nextStep);
    widget.onStepChanged(nextStep);
  }

  @override
  Widget build(BuildContext context) {
    return ExpertiseWizardShell(
      currentStep: _step,
      onStepChanged: _setStep,
      steps: [
        Step(
          title: const Text('Pasien & Petugas'),
          isActive: _step == 0,
          content: PatientStaffPanel(
            item: widget.item,
            user: widget.user,
            staffOptions: widget.staffOptions,
            staffValues: widget.staffValues,
            onChanged: widget.onChanged,
          ),
        ),
        Step(
          title: const Text('Sediaan Langsung'),
          isActive: _step == 1,
          content: _directSmear(),
        ),
        Step(
          title: const Text('Tes Kepekaan Antibiotik'),
          isActive: _step == 2,
          content: _antibioticSensitivity(),
        ),
        Step(
          title: const Text('Data Alat'),
          isActive: _step == 3,
          content: _toolData(),
        ),
        Step(
          title: const Text('Expertise'),
          isActive: _step == 4,
          content: _finalExpertise(),
        ),
      ],
    );
  }

  Widget _directSmear() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _sectionTitle('A. Sediaan Langsung'),
        _sectionTitle('1. Pewarnaan Gram', compact: true),
        _select('lsg_selepitel', 'Sel Epitel', _options('jsonselepitel')),
        _select('lsg_selradang', 'Sel Radang', _options('jsonselradang')),
        _select(
          'lsg_mikroorganisme',
          'Mikroorganisme',
          _options('jsonmikroorganisme'),
        ),
        _multiSelect(
          'lsg_mikroorganismeoptional',
          'Bisa memilih lebih dari satu',
          _options('jsonmikroorganismeoptional'),
        ),
        _sectionTitle('2. Pewarnaan Ziehl Neelsen', compact: true),
        _select(
          'lsg_pewarnaanziehlnielsen',
          'Pagi',
          _options('jsonpewarnaanziehlnielsen'),
        ),
        _select(
          'lsg_pewarnaanziehlnielsensewaktu',
          'Sewaktu',
          _options('jsonpewarnaanziehlnielsen'),
        ),
        _select(
          'lsg_pewarnaankoh',
          '3. Pewarnaan KOH',
          _options('jsonpewarnaankoh', _kohFallback),
        ),
        _text('lsg_pewarnaankohoptional', 'Pewarnaan KOH Manual'),
        _select(
          'lsg_pewarnaanneisser',
          '4. Pewarnaan Neisser',
          _options('jsonpewarnaanneisser'),
        ),
        _select(
          'lsg_pewarnaannegatif',
          '5. Pewarnaan Negatif',
          _options('jsonpewarnaannegatif'),
        ),
        _select(
          'lsg_pewarnaangiesma',
          '6. Pewarnaan Giemsa',
          _options('jsonpewarnaangiemsa', _giemsaFallback),
        ),
        _text('lsg_pewarnaangiesmaoptional', 'Pewarnaan Giemsa Manual'),
        _select(
          'lsg_pewarnaanspora',
          '7. Pewarnaan Spora',
          _options('jsonpewarnaanspora'),
        ),
        _text(
          'lsg_pewarnaanlain',
          '8. Pewarnaan Lain-Lain',
          minLines: 5,
          maxLines: 8,
        ),
        _nugentScore(),
        _saveDirectSmearButton(),
      ],
    );
  }

  Widget _saveDirectSmearButton() {
    return Padding(
      padding: const EdgeInsets.only(top: 4, bottom: 12),
      child: SizedBox(
        width: double.infinity,
        child: FilledButton.icon(
          onPressed: widget.saving
              ? null
              : () => widget.onSave('statuspewarnaanlsg'),
          icon: widget.saving
              ? const SizedBox.square(
                  dimension: 18,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Icon(Icons.save_outlined),
          label: const Text('SIMPAN PEWARNAAN LANGSUNG'),
        ),
      ),
    );
  }

  Widget _nugentScore() {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _sectionTitle('Nugent Score', compact: true),
            _select(
              'lsg_jumlahlactobacillus',
              'Lactobacillus - Jumlah Per Lapang',
              _options('jsonjumlahlactobacillus'),
            ),
            _select('lsg_lactobacillus', 'Lactobacillus - Skor', _scoreOptions),
            _select(
              'lsg_jumlahgardnerella',
              'Gardnerella - Jumlah Per Lapang',
              _options('jsonjumlahgardnerella'),
            ),
            _select('lsg_gardnerella', 'Gardnerella - Skor', _scoreOptions),
            _select(
              'lsg_jumlahmobiluncus',
              'Mobiluncus - Jumlah Per Lapang',
              _options('jsonjumlahmobiluncus'),
            ),
            _select('lsg_mobiluncus', 'Mobiluncus - Skor', _scoreOptions),
          ],
        ),
      ),
    );
  }

  Widget _antibioticSensitivity() {
    return AntibioticSensitivityPanel(
      textControllers: widget.textControllers,
      selectValues: widget.selectValues,
      onChanged: widget.onChanged,
    );
  }

  Widget _toolData() {
    return ToolDataPanel(
      textControllers: widget.textControllers,
      selectValues: widget.selectValues,
      onChanged: widget.onChanged,
    );
  }

  Widget _finalExpertise() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        ExpertiseHtmlEditor(
          controller: widget.textControllers['keterangan'] ??=
              TextEditingController(),
          label: 'Expertise',
        ),
        CheckboxListTile(
          value: widget.criticalValue,
          onChanged: (value) => widget.onCriticalChanged(value ?? false),
          contentPadding: EdgeInsets.zero,
          controlAffinity: ListTileControlAffinity.leading,
          title: const Text('Nilai Kritis'),
        ),
        FilledButton.icon(
          onPressed: widget.saving ? null : () => widget.onSave('Draft'),
          icon: widget.saving
              ? const SizedBox.square(
                  dimension: 18,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Icon(Icons.save_outlined),
          label: const Text('Save as Draft'),
        ),
        if (widget.isSupervisor) ...[
          OutlinedButton.icon(
            onPressed: widget.saving
                ? null
                : () => widget.onSave('preliminary'),
            icon: const Icon(Icons.done_all_outlined),
            label: const Text('Save Preliminary result'),
          ),
          OutlinedButton.icon(
            onPressed: widget.saving ? null : () => widget.onSave('verifikasi'),
            icon: const Icon(Icons.verified_outlined),
            label: const Text('Save Final Result'),
          ),
        ] else ...[
          OutlinedButton.icon(
            onPressed: widget.saving
                ? null
                : () => widget.onSave('Permohonan Verifikasi'),
            icon: const Icon(Icons.send_outlined),
            label: const Text('Save and Send To SPV'),
          ),
          OutlinedButton.icon(
            onPressed: widget.saving
                ? null
                : () => widget.onSave('Permohonan Verifikasi Preliminary'),
            icon: const Icon(Icons.outgoing_mail),
            label: const Text('Kirim SPV Preliminary'),
          ),
        ],
      ],
    );
  }

  List<String> _options(
    String key, [
    List<String> fallback = const ['Pilih Salah Satu'],
  ]) {
    final values = asList(
      widget.optionSets[key],
    ).map((item) => item.toString()).where((item) => item.isNotEmpty).toList();
    return values.isEmpty ? fallback : values;
  }

  Widget _sectionTitle(String title, {bool compact = false}) {
    return Padding(
      padding: EdgeInsets.only(bottom: compact ? 8 : 12),
      child: Text(
        title,
        style: Theme.of(context).textTheme.titleSmall?.copyWith(
          fontWeight: FontWeight.w800,
          color: const Color(0xFF0F766E),
        ),
      ),
    );
  }

  // ignore: unused_element
  Widget _toolSection({
    required String title,
    required String bacteriaField,
    String? antibioticField,
    required String sirField,
    required String colonyField,
    required String colonyTextField,
    required String printField,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _sectionTitle(title, compact: true),
            _text(bacteriaField, 'Bakteri'),
            if (antibioticField != null)
              _text(antibioticField, 'Set Antibiotik'),
            _select(sirField, 'SIR', _sirOptions),
            _select(colonyField, 'Hitung Koloni', _colonyOptions),
            _text(colonyTextField, 'Hitung Koloni Lainnya'),
            _select(printField, 'Cetak', const ['YA', 'TIDAK']),
          ],
        ),
      ),
    );
  }

  Widget _select(String name, String label, List<String> options) {
    final current = widget.selectValues[name];
    final effectiveOptions = [
      if (current != null && current.isNotEmpty && !options.contains(current))
        current,
      ...options,
    ];
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: DropdownButtonFormField<String>(
        initialValue:
            current != null &&
                current.isNotEmpty &&
                effectiveOptions.contains(current)
            ? current
            : null,
        isExpanded: true,
        decoration: InputDecoration(
          labelText: label,
          border: const OutlineInputBorder(),
        ),
        items: effectiveOptions
            .map(
              (option) => DropdownMenuItem(value: option, child: Text(option)),
            )
            .toList(),
        onChanged: (value) {
          widget.selectValues[name] = value ?? '';
          widget.onChanged();
        },
      ),
    );
  }

  Widget _multiSelect(String name, String label, List<String> options) {
    final selected = widget.multiValues[name] ?? <String>{};
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: CompactMultiSelectField(
        label: label,
        options: options,
        selected: selected,
        onChanged: (value) {
          widget.multiValues[name] = value;
          widget.onChanged();
        },
      ),
    );
  }

  Widget _text(
    String name,
    String label, {
    int minLines = 1,
    int maxLines = 1,
  }) {
    final controller = widget.textControllers[name] ??= TextEditingController();
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: TextField(
        controller: controller,
        minLines: minLines,
        maxLines: maxLines,
        decoration: InputDecoration(
          labelText: label,
          border: const OutlineInputBorder(),
        ),
      ),
    );
  }
}
