import 'package:flutter/material.dart';

import '../models/work_order.dart';

class WorkOrderDetailsScreen extends StatefulWidget {
  const WorkOrderDetailsScreen({this.order, super.key});

  final WorkOrder? order;

  @override
  State<WorkOrderDetailsScreen> createState() => _WorkOrderDetailsScreenState();
}

class _WorkOrderDetailsScreenState extends State<WorkOrderDetailsScreen> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _clientController;
  late final TextEditingController _phoneController;
  late final TextEditingController _addressController;

  bool get _readOnly => widget.order?.isCompleted ?? false;

  @override
  void initState() {
    super.initState();
    final details = widget.order?.details ?? const WorkOrderDetails();
    _clientController = TextEditingController(text: details.client);
    _phoneController = TextEditingController(text: details.phone);
    _addressController = TextEditingController(text: details.address);
  }

  @override
  void dispose() {
    _clientController.dispose();
    _phoneController.dispose();
    _addressController.dispose();
    super.dispose();
  }

  Future<void> _continue() async {
    if (!_readOnly && !_formKey.currentState!.validate()) return;

    final details = WorkOrderDetails(
      client: _clientController.text.trim(),
      phone: _phoneController.text.trim(),
      address: _addressController.text.trim(),
    );
    Navigator.of(context).pop(details);
  }

  String? _requiredField(String? value, String message) {
    if (value == null || value.trim().isEmpty) return message;
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_readOnly ? 'Datos de la OT' : 'Completar datos de la OT'),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.fromLTRB(20, 12, 20, 120),
          children: [
            Container(
              padding: const EdgeInsets.all(18),
              decoration: BoxDecoration(
                color: const Color(0xFFE7F1F0),
                borderRadius: BorderRadius.circular(18),
              ),
              child: const Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(Icons.assignment_ind_outlined, color: Color(0xFF0B5C5E)),
                  SizedBox(width: 13),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Encabezado de la orden',
                          style: TextStyle(
                            color: Color(0xFF163334),
                            fontSize: 17,
                            fontWeight: FontWeight.w800,
                          ),
                        ),
                        SizedBox(height: 5),
                        Text(
                          'Estos datos identificarán al cliente antes de '
                          'registrar el trabajo y las tareas.',
                          style: TextStyle(
                            color: Color(0xFF526665),
                            height: 1.35,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 26),
            TextFormField(
              key: const Key('client-field'),
              controller: _clientController,
              readOnly: _readOnly,
              autofocus: !_readOnly,
              textCapitalization: TextCapitalization.words,
              textInputAction: TextInputAction.next,
              decoration: const InputDecoration(
                labelText: 'Cliente',
                hintText: 'Nombre del cliente',
                prefixIcon: Icon(Icons.person_outline_rounded),
              ),
              validator: _readOnly
                  ? null
                  : (value) =>
                        _requiredField(value, 'Ingresa el nombre del cliente'),
            ),
            const SizedBox(height: 16),
            TextFormField(
              key: const Key('phone-field'),
              controller: _phoneController,
              readOnly: _readOnly,
              keyboardType: TextInputType.phone,
              textInputAction: TextInputAction.next,
              autofillHints: const [AutofillHints.telephoneNumber],
              decoration: const InputDecoration(
                labelText: 'Teléfono',
                hintText: '+56 9 1234 5678',
                prefixIcon: Icon(Icons.phone_outlined),
              ),
              validator: _readOnly
                  ? null
                  : (value) => _requiredField(
                      value,
                      'Ingresa el teléfono del cliente',
                    ),
            ),
            const SizedBox(height: 16),
            TextFormField(
              key: const Key('address-field'),
              controller: _addressController,
              readOnly: _readOnly,
              textCapitalization: TextCapitalization.sentences,
              textInputAction: TextInputAction.done,
              maxLines: 2,
              decoration: const InputDecoration(
                labelText: 'Dirección',
                hintText: 'Calle, número, comuna o referencia',
                prefixIcon: Icon(Icons.location_on_outlined),
              ),
              validator: _readOnly
                  ? null
                  : (value) => _requiredField(
                      value,
                      'Ingresa la dirección del trabajo',
                    ),
              onFieldSubmitted: (_) => _continue(),
            ),
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        top: false,
        child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 10, 20, 16),
          child: FilledButton.icon(
            key: const Key('continue-button'),
            onPressed: _continue,
            icon: Icon(
              _readOnly
                  ? Icons.visibility_outlined
                  : Icons.arrow_forward_rounded,
            ),
            label: Text(
              _readOnly
                  ? 'Ver trabajo y tareas'
                  : 'Continuar a trabajo y tareas',
            ),
          ),
        ),
      ),
    );
  }
}
