import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import '../../../core/models/vehicle.dart';
import '../providers/dashboard_providers.dart';

class VehicleFormScreen extends ConsumerStatefulWidget {
  final Vehicle? vehicle;

  const VehicleFormScreen({super.key, this.vehicle});

  @override
  ConsumerState<VehicleFormScreen> createState() => _VehicleFormScreenState();
}

class _VehicleFormScreenState extends ConsumerState<VehicleFormScreen> {
  final _formKey = GlobalKey<FormState>();
  bool _loading = false;

  late final _make = TextEditingController(text: widget.vehicle?.make);
  late final _model = TextEditingController(text: widget.vehicle?.model);
  late final _year = TextEditingController(
      text: widget.vehicle?.year.toString() ?? DateTime.now().year.toString());
  late final _plate =
      TextEditingController(text: widget.vehicle?.licensePlate);
  late final _rate = TextEditingController(
      text: widget.vehicle != null
          ? (widget.vehicle!.dailyRate / 100).toStringAsFixed(2)
          : '');
  late final _mileage = TextEditingController(
      text: widget.vehicle?.mileage?.toString());
  late final _seats = TextEditingController(
      text: widget.vehicle?.seats?.toString() ?? '5');
  late final _color = TextEditingController(text: widget.vehicle?.color ?? '');

  String _category = 'ECONOMY';
  String _transmission = 'AUTOMATIC';
  String _fuelType = 'GASOLINE';

  static const _categories = [
    'ECONOMY', 'COMPACT', 'MIDSIZE', 'FULLSIZE', 'SUV', 'LUXURY', 'VAN', 'TRUCK',
  ];
  static const _transmissions = ['AUTOMATIC', 'MANUAL'];
  static const _fuels = ['GASOLINE', 'DIESEL', 'ELECTRIC', 'HYBRID'];

  @override
  void initState() {
    super.initState();
    if (widget.vehicle != null) {
      _category = widget.vehicle!.category;
      _transmission = widget.vehicle!.transmission ?? 'AUTOMATIC';
      _fuelType = widget.vehicle!.fuelType ?? 'GASOLINE';
    }
  }

  @override
  void dispose() {
    for (final c in [_make, _model, _year, _plate, _rate, _mileage, _seats, _color]) {
      c.dispose();
    }
    super.dispose();
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _loading = true);
    try {
      final data = {
        'make': _make.text.trim(),
        'model': _model.text.trim(),
        'year': int.parse(_year.text),
        'licensePlate': _plate.text.trim(),
        'dailyRate': (double.parse(_rate.text) * 100).round(),
        'category': _category,
        'transmission': _transmission,
        'fuelType': _fuelType,
        'seats': int.tryParse(_seats.text) ?? 5,
        if (_mileage.text.isNotEmpty) 'mileage': int.parse(_mileage.text),
        if (_color.text.isNotEmpty) 'color': _color.text.trim(),
      };
      final svc = ref.read(vehicleServiceProvider);
      if (widget.vehicle == null) {
        await svc.createVehicle(data);
      } else {
        await svc.updateVehicle(widget.vehicle!.id, data);
      }
      if (mounted) Navigator.of(context).pop(true);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Error: $e')));
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isEdit = widget.vehicle != null;
    return Scaffold(
      appBar: AppBar(
        title: Text(isEdit ? 'Edit Vehicle' : 'New Vehicle'),
        actions: [
          if (_loading)
            const Padding(
              padding: EdgeInsets.all(16),
              child: SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2)),
            )
          else
            TextButton(
              onPressed: _submit,
              child: const Text('Save'),
            ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            _section('Basic Info', [
              _field('Make', _make, required: true),
              _field('Model', _model, required: true),
              _field('Year', _year, required: true,
                  inputType: TextInputType.number),
              _field('License Plate', _plate, required: true),
              _field('Color', _color),
            ]),
            const SizedBox(height: 16),
            _section('Specs', [
              _dropdown('Category', _category, _categories,
                  (v) => setState(() => _category = v!)),
              _dropdown('Transmission', _transmission, _transmissions,
                  (v) => setState(() => _transmission = v!)),
              _dropdown('Fuel Type', _fuelType, _fuels,
                  (v) => setState(() => _fuelType = v!)),
              _field('Seats', _seats, inputType: TextInputType.number),
              _field('Mileage (km)', _mileage,
                  inputType: TextInputType.number),
            ]),
            const SizedBox(height: 16),
            _section('Pricing', [
              _field('Daily Rate (\$)', _rate,
                  required: true, inputType: TextInputType.number),
            ]),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _loading ? null : _submit,
              style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(48),
              ),
              child: Text(isEdit ? 'Save Changes' : 'Create Vehicle'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _section(String title, List<Widget> children) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title,
            style: const TextStyle(
                fontSize: 13,
                fontWeight: FontWeight.w600,
                color: Color(0xFF6B7280))),
        const SizedBox(height: 10),
        Card(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Column(children: children),
          ),
        ),
      ],
    );
  }

  Widget _field(String label, TextEditingController ctrl,
      {bool required = false, TextInputType? inputType}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: TextFormField(
        controller: ctrl,
        keyboardType: inputType,
        decoration: InputDecoration(labelText: label),
        validator: required
            ? (v) => v == null || v.isEmpty ? 'Required' : null
            : null,
      ),
    );
  }

  Widget _dropdown(String label, String value, List<String> items,
      ValueChanged<String?> onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: InputDecorator(
        decoration: InputDecoration(labelText: label),
        child: DropdownButton<String>(
          value: value,
          isExpanded: true,
          underline: const SizedBox(),
          items: items
              .map((e) => DropdownMenuItem(value: e, child: Text(e)))
              .toList(),
          onChanged: onChanged,
        ),
      ),
    );
  }
}

class VehiclePhotosSheet extends ConsumerStatefulWidget {
  final String vehicleId;
  final List<String> currentPhotos;

  const VehiclePhotosSheet({
    super.key,
    required this.vehicleId,
    required this.currentPhotos,
  });

  @override
  ConsumerState<VehiclePhotosSheet> createState() => _VehiclePhotosSheetState();
}

class _VehiclePhotosSheetState extends ConsumerState<VehiclePhotosSheet> {
  bool _uploading = false;

  Future<void> _pickAndUpload() async {
    final picker = ImagePicker();
    final files = await picker.pickMultiImage(imageQuality: 80);
    if (files.isEmpty) return;
    setState(() => _uploading = true);
    try {
      await ref
          .read(vehicleServiceProvider)
          .uploadPhotos(widget.vehicleId, files.map((f) => f.path).toList());
      if (mounted) Navigator.of(context).pop(true);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Upload failed: $e')));
      }
    } finally {
      if (mounted) setState(() => _uploading = false);
    }
  }

  Future<void> _deletePhoto(int idx) async {
    try {
      await ref
          .read(vehicleServiceProvider)
          .deletePhoto(widget.vehicleId, idx);
      if (mounted) Navigator.of(context).pop(true);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Delete failed: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                const Text('Photos',
                    style:
                        TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                const Spacer(),
                if (_uploading)
                  const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2))
                else
                  IconButton(
                    icon: const Icon(Icons.add_photo_alternate_outlined),
                    onPressed: _pickAndUpload,
                  ),
              ],
            ),
            const SizedBox(height: 12),
            if (widget.currentPhotos.isEmpty)
              const Padding(
                padding: EdgeInsets.all(24),
                child: Text('No photos yet',
                    style: TextStyle(color: Color(0xFF9CA3AF))),
              )
            else
              SizedBox(
                height: 100,
                child: ListView.separated(
                  scrollDirection: Axis.horizontal,
                  itemCount: widget.currentPhotos.length,
                  separatorBuilder: (_, _) => const SizedBox(width: 8),
                  itemBuilder: (_, i) => Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.network(
                          widget.currentPhotos[i],
                          width: 100,
                          height: 100,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Positioned(
                        top: 2,
                        right: 2,
                        child: GestureDetector(
                          onTap: () => _deletePhoto(i),
                          child: Container(
                            padding: const EdgeInsets.all(2),
                            decoration: const BoxDecoration(
                              color: Color(0xFFE02424),
                              shape: BoxShape.circle,
                            ),
                            child: const Icon(Icons.close,
                                size: 14, color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }
}
