import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, CheckCircle2, Save, FileText, Calendar, Clock, Wrench, ChevronRight } from 'lucide-react';
import api from '../services/api';
import { useToast } from '../context/use-toast';
import clsx from 'clsx';

export default function ResolveClaimModal({ claim, listing, onClose, onSuccess }: any) {
  const { showToast } = useToast();
  const [loading, setLoading] = useState(false);
  const [showTools, setShowTools] = useState(false);

  // Usamos valores defensivos para que no rompa si listing es undefined
  const [solutionData, setSolutionData] = useState({
    solution: '',
    applyAdjustments: false,
    newPrintText: listing?.printText || listing?.description || '',
    newStartDate: listing?.printStartDate ? listing.printStartDate.split('T')[0] : '',
    newDaysCount: listing?.printDaysCount || 3
  });

  const handleResolve = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      // Enviamos la resolución + los ajustes técnicos
      await api.put(`/claims/${claim.id}/resolve`, {
        solution: solutionData.solution,
        // Solo enviamos ajustes si el switch está activo
        newPrintText: solutionData.applyAdjustments ? solutionData.newPrintText : null,
        newStartDate: solutionData.applyAdjustments ? solutionData.newStartDate : null,
        newDaysCount: solutionData.applyAdjustments ? solutionData.newDaysCount : null,
      });

      showToast("Solución aplicada y aviso actualizado con éxito", "success");
      onSuccess();
      onClose();
    } catch (error) {
      showToast("Error al procesar la resolución técnica", "error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-sm z-[400] flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }}
        className="bg-white w-full max-w-2xl rounded-[2.5rem] shadow-2xl overflow-hidden border border-slate-100"
      >
        <div className="p-6 bg-emerald-600 text-white flex justify-between items-center">
          <div className="flex items-center gap-3">
            <CheckCircle2 size={24} />
            <h3 className="text-lg font-black uppercase tracking-tight">Aplicar Solución Técnica</h3>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-xl"><X /></button>
        </div>

        <form onSubmit={handleResolve} className="p-8 space-y-6 max-h-[80vh] overflow-y-auto custom-scrollbar">

          {/* INFO DEL RECLAMO */}
          <div className="bg-slate-50 p-4 rounded-2xl border border-slate-100">
            <p className="text-[10px] font-black text-slate-400 uppercase mb-1">Motivo: {claim.claimType}</p>
            <p className="text-xs font-bold text-slate-700 italic">"{claim.description}"</p>
          </div>

          {/* TEXTO DE LA SOLUCIÓN */}
          <div className="space-y-2">
            <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1">Informe de Resolución</label>
            <textarea
              required
              className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none focus:border-emerald-500 font-bold text-slate-700 min-h-[100px] resize-none text-sm"
              placeholder="Describa qué acciones tomó para resolver este reclamo..."
              value={solutionData.solution}
              onChange={e => setSolutionData({ ...solutionData, solution: e.target.value })}
            />
          </div>

          {/* HERRAMIENTAS DE AJUSTE (Técnico) */}
          <div className="pt-4 border-t border-slate-100">
            <button
              type="button"
              onClick={() => {
                setShowTools(!showTools);
                setSolutionData({ ...solutionData, applyAdjustments: !showTools });
              }}
              className={clsx(
                "w-full p-4 rounded-2xl flex items-center justify-between transition-all",
                showTools ? "bg-blue-600 text-white shadow-lg" : "bg-blue-50 text-blue-600 hover:bg-blue-100"
              )}
            >
              <div className="flex items-center gap-3">
                <Wrench size={18} />
                <span className="text-xs font-black uppercase tracking-widest">Habilitar Ajustes Técnicos</span>
              </div>
              <ChevronRight className={clsx("transition-transform", showTools && "rotate-90")} size={18} />
            </button>

            <AnimatePresence>
              {showTools && (
                <motion.div
                  initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} exit={{ height: 0, opacity: 0 }}
                  className="overflow-hidden"
                >
                  <div className="p-6 mt-2 space-y-6 bg-slate-50 rounded-3xl border-2 border-blue-100">

                    <div className="space-y-2">
                      <label className="text-[10px] font-black text-blue-600 uppercase flex items-center gap-2">
                        <FileText size={12} /> Corrección de Texto (Imprenta)
                      </label>
                      <textarea
                        className="w-full p-4 bg-white border border-blue-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 font-mono text-xs uppercase"
                        value={solutionData.newPrintText}
                        onChange={e => setSolutionData({ ...solutionData, newPrintText: e.target.value })}
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <label className="text-[10px] font-black text-blue-600 uppercase flex items-center gap-2">
                          <Calendar size={12} /> Nueva Fecha Inicio
                        </label>
                        <input
                          type="date"
                          className="w-full p-3 bg-white border border-blue-200 rounded-xl text-xs font-bold"
                          value={solutionData.newStartDate}
                          onChange={e => setSolutionData({ ...solutionData, newStartDate: e.target.value })}
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-[10px] font-black text-blue-600 uppercase flex items-center gap-2">
                          <Clock size={12} /> Días de extensión
                        </label>
                        <input
                          type="number"
                          className="w-full p-3 bg-white border border-blue-200 rounded-xl text-xs font-bold"
                          value={solutionData.newDaysCount}
                          onChange={e => setSolutionData({ ...solutionData, newDaysCount: parseInt(e.target.value) })}
                        />
                      </div>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          <button
            type="submit" disabled={loading}
            className="w-full py-5 bg-emerald-600 text-white font-black uppercase text-xs tracking-[.2em] rounded-2xl shadow-xl shadow-emerald-200 hover:bg-emerald-700 transition-all flex items-center justify-center gap-2"
          >
            <Save size={18} /> {loading ? 'Procesando...' : 'Confirmar y Aplicar Cambios'}
          </button>
        </form>
      </motion.div>
    </div>
  );
}