import 'package:flutter/material.dart';
import 'model/input_cell_model.dart';
import 'model/input_data_default_code.dart';

class InputFormCell extends StatefulWidget {
  final InputCellModel model;
  final VoidCallback? onChanged;
  final bool isViewOnly;

  const InputFormCell({
    super.key,
    required this.model,
    this.onChanged,
    this.isViewOnly = false,
  });

  @override
  State<InputFormCell> createState() => _InputFormCellState();
}

class _InputFormCellState extends State<InputFormCell> {
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(
      text: widget.model.content ?? widget.model.defaultValue ?? '',
    );
  }

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

  @override
  Widget build(BuildContext context) {
    final isEditable = (widget.model.enableEdit ?? true)  && !widget.isViewOnly;
    final isRequired = widget.model.require == true;
    final title = isRequired ? '${widget.model.title ?? ''} *' : widget.model.title ?? '';
    final isBirthDate = widget.model.inputDefaultType == InputDataDefaultCode.birthDate;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 6),
        Container(
          decoration: BoxDecoration(
            color: isEditable ? Colors.white : Colors.grey.shade200,
            border: Border.all(color: Colors.grey.shade400),
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            children: [
              Expanded(
                child: TextFormField(
                  enabled: isEditable && !isBirthDate,
                  controller: _controller,
                  maxLength: widget.model.maxLength,
                  keyboardType: widget.model.keyboardType,
                  decoration: InputDecoration(
                    hintText: widget.model.placeholder,
                    hintStyle: const TextStyle(color: Colors.grey),
                    border: InputBorder.none,
                    counterText: '',
                  ),
                  style: const TextStyle(fontSize: 14, color: Colors.black),
                  onChanged: (value) {
                    widget.model.content = value; // ✅ update model
                    widget.onChanged?.call();     // ✅ callback để validate bên ngoài
                  },
                  readOnly: isBirthDate,
                  onTap: () {
                    if (isBirthDate) _pickDate();
                  },
                ),
              ),
              if (isBirthDate)
                IconButton(
                  icon: const Icon(Icons.calendar_today_outlined, size: 20),
                  onPressed: isEditable ? _pickDate : null,
                ),
            ],
          ),
        ),

      ],
    );
  }

  Future<void> _pickDate() async {
    DateTime? initialDate = DateTime.tryParse(_controller.text) ?? DateTime(2000);
    DateTime? picked = await showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
    );
    if (picked != null) {
      final formatted = "${picked.day.toString().padLeft(2, '0')}/${picked.month.toString().padLeft(2, '0')}/${picked.year}";
      _controller.text = formatted;
      widget.model.content = formatted;
      widget.onChanged?.call();
    }
  }
}

