import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import '../../core/app_colors.dart';
import '../../database/db_helper.dart';
import '../../services/auth_service.dart';
import '../shared/reporte_chat_screen.dart';

class AdminReporteDetalleScreen extends StatefulWidget {
  final Map<String, dynamic> reporte;
  const AdminReporteDetalleScreen({super.key, required this.reporte});
  @override State<AdminReporteDetalleScreen> createState() => _AdminReporteDetalleScreenState();
}

class _AdminReporteDetalleScreenState extends State<AdminReporteDetalleScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabs;
  late Map<String, dynamic> _r;
  List<Map<String, dynamic>> _notas = [];
  List<Map<String, dynamic>> _evidencias = [];
  int _chatUnread = 0;
  final _notaCtrl = TextEditingController();
  final _pieCtrl  = TextEditingController();
  File? _evidFoto;
  bool _loadingNota = false, _loadingEv = false;
  final _picker = ImagePicker();

  static const _estados = [
    'PENDIENTE', 'EN_REVISION', 'EN_PROCESO', 'RESUELTO', 'COMPLETADO'
  ];
  static const _estadoLabels = {
    'PENDIENTE':   'Pendiente',
    'EN_REVISION': 'En Revision',
    'EN_PROCESO':  'En Proceso',
    'RESUELTO':    'Resuelto',
    'COMPLETADO':  'Completado',
  };

  @override
  void initState() {
    super.initState();
    _r = Map.from(widget.reporte);
    _tabs = TabController(length: 3, vsync: this);
    _load();
  }

  Future<void> _load() async {
    final id = _r['id'] as int;
    final n  = await DbHelper.getReporteNotas(id);
    final e  = await DbHelper.getReporteEvidencias(id);
    final u  = await DbHelper.getChatUnread(id, 'ADMINISTRADOR');
    if (mounted) setState(() { _notas = n; _evidencias = e; _chatUnread = u; });
  }

  Color _estadoColor(String s) {
    switch (s) {
      case 'COMPLETADO':  return AppColors.verdeExito;
      case 'RESUELTO':    return Colors.teal;
      case 'EN_PROCESO':  return AppColors.azulInfo;
      case 'EN_REVISION': return AppColors.naranjaAlerta;
      default:            return AppColors.grisTexto;
    }
  }

  Future<void> _cambiarEstado(String nuevoEstado) async {
    await DbHelper.updateReporteEstado(_r['id'] as int, nuevoEstado);
    setState(() => _r['estado'] = nuevoEstado);
    if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text('Estado actualizado a: ${_estadoLabels[nuevoEstado]}'),
        backgroundColor: _estadoColor(nuevoEstado)));
  }

  Future<void> _agregarNota() async {
    if (_notaCtrl.text.trim().isEmpty) return;
    final auth = context.read<AuthService>();
    setState(() => _loadingNota = true);
    await DbHelper.insertReporteNota(
        _r['id'] as int, auth.currentUser!.id!,
        auth.currentUser!.nombre, _notaCtrl.text.trim());
    _notaCtrl.clear();
    await _load();
    setState(() => _loadingNota = false);
  }

  Future<void> _agregarEvidencia() async {
    if (_pieCtrl.text.trim().isEmpty && _evidFoto == null) return;
    final auth = context.read<AuthService>();
    setState(() => _loadingEv = true);
    await DbHelper.insertReporteEvidencia(
        _r['id'] as int, auth.currentUser!.id!,
        _pieCtrl.text.trim(), _evidFoto?.path);
    _pieCtrl.clear();
    setState(() => _evidFoto = null);
    await _load();
    setState(() => _loadingEv = false);
  }

  Future<void> _pickFoto() async {
    final p = await _picker.pickImage(source: ImageSource.camera, imageQuality: 70, maxWidth: 1024);
    if (p != null && mounted) setState(() => _evidFoto = File(p.path));
  }

  @override
  Widget build(BuildContext context) {
    final estado   = _r['estado'] as String? ?? 'PENDIENTE';
    final isClosed = estado == 'COMPLETADO';
    final folio    = 'RPT-${(_r['id'] as int).toString().padLeft(5,'0')}';

    return Scaffold(
      backgroundColor: AppColors.grisFondo,
      appBar: AppBar(
        backgroundColor: AppColors.guindaPrimary, foregroundColor: Colors.white,
        title: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('Reporte $folio', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
          Text(_r['colonia'] as String? ?? '', style: const TextStyle(fontSize: 11, color: Colors.white70)),
        ]),
        bottom: TabBar(controller: _tabs, indicatorColor: AppColors.dorado,
          labelColor: AppColors.dorado, unselectedLabelColor: Colors.white70,
          labelStyle: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
          tabs: [
            const Tab(icon: Icon(Icons.info_outline, size: 18), text: 'Detalle'),
            const Tab(icon: Icon(Icons.sticky_note_2_outlined, size: 18), text: 'Notas'),
            Tab(icon: Stack(clipBehavior: Clip.none, children: [
              const Icon(Icons.chat_outlined, size: 18),
              if (_chatUnread > 0) Positioned(right: -4, top: -4,
                child: Container(width: 10, height: 10,
                  decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle))),
            ]), text: 'Chat'),
          ]),
      ),
      body: TabBarView(controller: _tabs, children: [
        // ── TAB 0: Detalle + cambio estado + evidencias ──────────────────
        _buildDetalleTab(estado, isClosed, folio),
        // ── TAB 1: Notas internas del admin ──────────────────────────────
        _buildNotasTab(isClosed),
        // ── TAB 2: Chat con ciudadano ─────────────────────────────────────
        ReporteChatScreen(reporteId: _r['id'] as int,
            folio: folio, isClosed: isClosed),
      ]),
    );
  }

  Widget _buildDetalleTab(String estado, bool isClosed, String folio) =>
      SingleChildScrollView(padding: const EdgeInsets.all(14), child: Column(
        crossAxisAlignment: CrossAxisAlignment.start, children: [
        // Info básica
        Card(child: Padding(padding: const EdgeInsets.all(14), child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(children: [
            Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text('Reportado por: ${_r['user_nombre'] ?? 'Ciudadano'}',
                  style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13)),
              Text(_r['user_email'] ?? '',
                  style: const TextStyle(color: AppColors.grisTexto, fontSize: 11)),
            ])),
            _EstadoBadge(estado: estado, color: _estadoColor(estado)),
          ]),
          const Divider(),
          Text('Tipo: ${_r['tipo'] ?? ''}',
              style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 12)),
          Text('Colonia: ${_r['colonia'] ?? ''} — Ruta: ${_r['route_id'] ?? ''}',
              style: const TextStyle(color: AppColors.grisTexto, fontSize: 12)),
          const SizedBox(height: 6),
          Text(_r['descripcion'] ?? '',
              style: const TextStyle(fontSize: 13, height: 1.4)),
          if (_r['foto_path'] != null && (_r['foto_path'] as String).isNotEmpty) ...[
            const SizedBox(height: 8),
            const Text('Foto del ciudadano:',
                style: TextStyle(fontWeight: FontWeight.w600, fontSize: 12)),
            const SizedBox(height: 4),
            ClipRRect(borderRadius: BorderRadius.circular(8),
              child: Image.file(File(_r['foto_path'] as String),
                  height: 140, width: double.infinity, fit: BoxFit.cover)),
          ],
        ]))),
        const SizedBox(height: 12),

        // Cambiar estado
        if (!isClosed) ...[
          const Text('Cambiar Estado', style: TextStyle(fontWeight: FontWeight.bold,
              color: AppColors.guindaPrimary, fontSize: 14)),
          const SizedBox(height: 8),
          Wrap(spacing: 8, runSpacing: 8, children: _estados.map((e) {
            final isActual = e == estado;
            return ActionChip(
              label: Text(_estadoLabels[e]!, style: TextStyle(
                  fontWeight: isActual ? FontWeight.bold : FontWeight.normal,
                  fontSize: 12, color: isActual ? Colors.white : _estadoColor(e))),
              backgroundColor: isActual ? _estadoColor(e) : _estadoColor(e).withOpacity(0.1),
              side: BorderSide(color: _estadoColor(e)),
              onPressed: isActual ? null : () => _cambiarEstado(e),
            );
          }).toList()),
          const SizedBox(height: 16),
        ],

        // Evidencias del admin
        Row(children: [
          const Expanded(child: Text('Evidencias dla Direccion General',
              style: TextStyle(fontWeight: FontWeight.bold,
                  color: AppColors.guindaPrimary, fontSize: 14))),
          Text('${_evidencias.length}',
              style: const TextStyle(color: AppColors.grisTexto, fontSize: 12)),
        ]),
        const SizedBox(height: 8),

        if (!isClosed) Card(child: Padding(padding: const EdgeInsets.all(12), child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: [
          const Text('Agregar evidencia de atencion',
              style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13)),
          const SizedBox(height: 8),
          TextField(controller: _pieCtrl, maxLines: 2,
              decoration: const InputDecoration(
                  hintText: 'Describe la evidencia (ej. Se reparo la calle)...',
                  border: OutlineInputBorder(), isDense: true, filled: true, fillColor: Colors.white)),
          const SizedBox(height: 8),
          Row(children: [
            Expanded(child: _evidFoto == null
                ? OutlinedButton.icon(
                    onPressed: _pickFoto,
                    icon: const Icon(Icons.camera_alt, size: 16),
                    label: const Text('Tomar foto', style: TextStyle(fontSize: 12)),
                    style: OutlinedButton.styleFrom(foregroundColor: AppColors.guindaPrimary,
                        side: const BorderSide(color: AppColors.guindaPrimary)))
                : Stack(children: [
                    ClipRRect(borderRadius: BorderRadius.circular(6),
                      child: Image.file(_evidFoto!, height: 70, width: double.infinity, fit: BoxFit.cover)),
                    Positioned(top: 4, right: 4,
                      child: GestureDetector(onTap: () => setState(() => _evidFoto = null),
                        child: CircleAvatar(radius: 12, backgroundColor: Colors.red.withOpacity(0.85),
                          child: const Icon(Icons.close, color: Colors.white, size: 12)))),
                  ])),
            const SizedBox(width: 8),
            ElevatedButton(
              onPressed: _loadingEv ? null : _agregarEvidencia,
              style: ElevatedButton.styleFrom(backgroundColor: AppColors.guindaPrimary,
                  foregroundColor: Colors.white, minimumSize: const Size(80, 42)),
              child: _loadingEv
                  ? const SizedBox(width: 16, height: 16,
                      child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                  : const Text('Guardar', style: TextStyle(fontSize: 12))),
          ]),
        ]))),

        if (_evidencias.isNotEmpty) ...[
          const SizedBox(height: 8),
          ..._evidencias.map((ev) => Card(margin: const EdgeInsets.only(bottom: 6),
            child: Padding(padding: const EdgeInsets.all(10), child: Column(
              crossAxisAlignment: CrossAxisAlignment.start, children: [
              Row(children: [
                const Icon(Icons.verified, color: AppColors.guindaPrimary, size: 14),
                const SizedBox(width: 4),
                Text(ev['admin_nombre'] as String? ?? 'Admin',
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 11,
                        color: AppColors.guindaPrimary)),
                const Spacer(),
                Text(_timeAgo(ev['fecha'] as String? ?? ''),
                    style: const TextStyle(fontSize: 10, color: AppColors.grisTexto)),
              ]),
              const SizedBox(height: 4),
              Text(ev['pie_imagen'] as String? ?? '',
                  style: const TextStyle(fontSize: 12, height: 1.4)),
              if ((ev['foto_path'] as String?) != null &&
                  (ev['foto_path'] as String).isNotEmpty) ...[
                const SizedBox(height: 6),
                ClipRRect(borderRadius: BorderRadius.circular(6),
                  child: Image.file(File(ev['foto_path'] as String),
                      height: 120, width: double.infinity, fit: BoxFit.cover)),
              ],
            ])))),
        ],
        const SizedBox(height: 20),
      ]));

  Widget _buildNotasTab(bool isClosed) =>
      Column(children: [
        Expanded(child: _notas.isEmpty
            ? Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                const Icon(Icons.sticky_note_2_outlined, color: AppColors.grisTexto, size: 48),
                const SizedBox(height: 12),
                const Text('Sin notas internas', style: TextStyle(color: AppColors.grisTexto)),
              ]))
            : ListView.builder(
                padding: const EdgeInsets.all(12),
                itemCount: _notas.length,
                itemBuilder: (_, i) {
                  final n = _notas[i];
                  return Card(margin: const EdgeInsets.only(bottom: 8),
                    color: Colors.amber.shade50,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8),
                        side: BorderSide(color: Colors.amber.shade200)),
                    child: Padding(padding: const EdgeInsets.all(10), child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Row(children: [
                        const Icon(Icons.person, color: AppColors.grisTexto, size: 14),
                        const SizedBox(width: 4),
                        Text(n['admin_nombre'] as String? ?? '',
                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 11)),
                        const Spacer(),
                        Text(_timeAgo(n['fecha'] as String? ?? ''),
                            style: const TextStyle(fontSize: 10, color: AppColors.grisTexto)),
                      ]),
                      const SizedBox(height: 4),
                      Text(n['nota'] as String? ?? '',
                          style: const TextStyle(fontSize: 13, height: 1.4)),
                    ])));
                })),
        if (!isClosed) Container(
          padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), color: Colors.white,
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            const Text('Nueva nota interna (solo visible para admins)',
                style: TextStyle(fontSize: 11, color: AppColors.grisTexto)),
            const SizedBox(height: 6),
            Row(children: [
              Expanded(child: TextField(controller: _notaCtrl, maxLines: 2,
                  decoration: const InputDecoration(
                      hintText: 'Escribe una nota interna...',
                      border: OutlineInputBorder(), isDense: true,
                      filled: true, fillColor: AppColors.grisFondo))),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: _loadingNota ? null : _agregarNota,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.amber.shade700,
                    foregroundColor: Colors.white, minimumSize: const Size(70, 48)),
                child: _loadingNota
                    ? const SizedBox(width: 16, height: 16,
                        child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                    : const Icon(Icons.add, size: 20)),
            ]),
          ])),
      ]);

  String _timeAgo(String fechaStr) {
    final f = DateTime.tryParse(fechaStr);
    if (f == null) return '';
    final diff = DateTime.now().difference(f);
    if (diff.inMinutes < 1) return 'Ahora';
    if (diff.inMinutes < 60) return 'Hace ${diff.inMinutes} min';
    if (diff.inHours < 24) return 'Hace ${diff.inHours}h';
    return '${f.day}/${f.month}/${f.year}';
  }

  @override void dispose() { _tabs.dispose(); _notaCtrl.dispose(); _pieCtrl.dispose(); super.dispose(); }
}

class _EstadoBadge extends StatelessWidget {
  final String estado; final Color color;
  const _EstadoBadge({required this.estado, required this.color});
  @override
  Widget build(BuildContext context) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
    decoration: BoxDecoration(color: color.withOpacity(0.12), borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.4))),
    child: Text(estado, style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: color)));
}
