import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { getAttendanceById, getUserById } from '../services/dataService';
import { Attendance, User, FunnelStage } from '../types';
import { ArrowLeft, CheckCircle2, AlertCircle, Clock, Calendar, MessageSquare, ShoppingBag, Award, TrendingUp } from 'lucide-react';

export const AttendanceDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [data, setData] = useState<Attendance | undefined>();
  const [agent, setAgent] = useState<User | undefined>();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadData = async () => {
      if (id) {
        setLoading(true);
        try {
          const att = await getAttendanceById(id);
          setData(att);
          if (att) {
            const u = await getUserById(att.user_id);
            setAgent(u);
          }
        } catch (error) {
          console.error("Error loading details", error);
        } finally {
          setLoading(false);
        }
      }
    };
    loadData();
  }, [id]);

  if (loading) return <div className="p-12 text-center text-slate-400">Carregando detalhes...</div>;
  if (!data) return <div className="p-12 text-center text-slate-500">Registro de atendimento não encontrado</div>;

  const getStageColor = (stage: FunnelStage) => {
    switch (stage) {
      case FunnelStage.WON: return 'text-green-700 bg-green-50 border-green-200';
      case FunnelStage.LOST: return 'text-red-700 bg-red-50 border-red-200';
      default: return 'text-blue-700 bg-blue-50 border-blue-200';
    }
  };

  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-green-500';
    if (score >= 60) return 'text-yellow-500';
    return 'text-red-500';
  };

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      {/* Top Nav & Context */}
      <div className="flex items-center justify-between">
        <Link 
          to={`/users/${data.user_id}`} 
          className="flex items-center gap-2 text-slate-500 hover:text-slate-900 transition-colors text-sm font-medium"
        >
          <ArrowLeft size={16} /> Voltar para Histórico
        </Link>
        <div className="text-sm text-slate-400 font-mono">ID: {data.id}</div>
      </div>

      {/* Hero Header */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 md:p-8">
        <div className="flex flex-col md:flex-row justify-between gap-6">
          <div className="space-y-4">
             <div className="flex flex-wrap items-center gap-3">
              <span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wide border ${getStageColor(data.funnel_stage)}`}>
                {data.funnel_stage}
              </span>
              <span className="flex items-center gap-1.5 text-slate-500 text-sm">
                <Calendar size={14} /> {new Date(data.created_at).toLocaleString('pt-BR')}
              </span>
              <span className="flex items-center gap-1.5 text-slate-500 text-sm">
                 <MessageSquare size={14} /> {data.origin}
              </span>
            </div>
            <h1 className="text-2xl md:text-3xl font-bold text-slate-900 leading-tight">
              {data.summary}
            </h1>
            {agent && (
              <div className="flex items-center gap-3 pt-2">
                <img src={agent.avatar_url} alt="" className="w-8 h-8 rounded-full border border-slate-200" />
                <span className="text-sm font-medium text-slate-700">Agente: <span className="text-slate-900">{agent.name}</span></span>
              </div>
            )}
          </div>

          <div className="flex flex-col items-center justify-center min-w-[140px] p-6 bg-slate-50 rounded-xl border border-slate-100">
            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Nota de Qualidade</span>
            <div className={`text-5xl font-black ${getScoreColor(data.score)}`}>
              {data.score}
            </div>
            <span className="text-xs font-medium text-slate-400 mt-1">de 100</span>
          </div>
        </div>
      </div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        {/* Left Column: Analysis */}
        <div className="lg:col-span-2 space-y-6">
          
          {/* Summary / Transcript Stub */}
          <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
            <h3 className="text-base font-bold text-slate-900 mb-4 flex items-center gap-2">
              <MessageSquare size={18} className="text-slate-400" />
              Resumo da Interação
            </h3>
            <p className="text-slate-600 leading-relaxed text-sm">
              {data.summary} O cliente perguntou sobre detalhes específicos relacionados ao <span className="font-medium text-slate-800">{data.product_requested}</span>. 
              As discussões envolveram níveis de preços, prazos de implementação e potenciais descontos por volume. 
              A interação foi concluída com {data.converted ? 'uma venda realizada' : 'o cliente pedindo mais tempo para decidir'}.
            </p>
          </div>

          {/* Feedback Section */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Points of Attention */}
            <div className="bg-white rounded-xl border border-red-100 shadow-sm overflow-hidden">
              <div className="px-5 py-3 bg-red-50/50 border-b border-red-100 flex items-center gap-2">
                <AlertCircle size={18} className="text-red-500" />
                <h3 className="font-bold text-red-900 text-sm">Pontos de Atenção</h3>
              </div>
              <div className="p-5">
                {data.attention_points && data.attention_points.length > 0 ? (
                  <ul className="space-y-3">
                    {data.attention_points.map((pt, idx) => (
                      <li key={idx} className="flex gap-3 text-sm text-slate-700">
                        <span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-red-400 shrink-0" />
                        {pt}
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p className="text-sm text-slate-400 italic">Nenhum problema detectado.</p>
                )}
              </div>
            </div>

            {/* Points of Improvement */}
            <div className="bg-white rounded-xl border border-blue-100 shadow-sm overflow-hidden">
              <div className="px-5 py-3 bg-blue-50/50 border-b border-blue-100 flex items-center gap-2">
                <CheckCircle2 size={18} className="text-blue-500" />
                <h3 className="font-bold text-blue-900 text-sm">Dicas de Melhoria</h3>
              </div>
              <div className="p-5">
                 {data.improvement_points && data.improvement_points.length > 0 ? (
                  <ul className="space-y-3">
                    {data.improvement_points.map((pt, idx) => (
                      <li key={idx} className="flex gap-3 text-sm text-slate-700">
                        <span className="mt-1.5 w-1.5 h-1.5 rounded-full bg-blue-400 shrink-0" />
                        {pt}
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p className="text-sm text-slate-400 italic">Continue o bom trabalho!</p>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Right Column: Metadata & Metrics */}
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5">
            <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Métricas de Performance</h3>
            <div className="space-y-4">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-white rounded-md border border-slate-100 text-blue-500"><Clock size={16} /></div>
                  <span className="text-sm font-medium text-slate-600">Primeira Resposta</span>
                </div>
                <span className="text-sm font-bold text-slate-900">{data.first_response_time_min} min</span>
              </div>
              
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-white rounded-md border border-slate-100 text-purple-500"><TrendingUp size={16} /></div>
                  <span className="text-sm font-medium text-slate-600">Tempo Atendimento</span>
                </div>
                <span className="text-sm font-bold text-slate-900">{data.handling_time_min} min</span>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-5">
            <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Contexto de Vendas</h3>
            <div className="space-y-4">
              <div className="space-y-1">
                <span className="text-xs text-slate-500 font-medium">Produto Solicitado</span>
                <div className="flex items-center gap-2 font-semibold text-slate-800">
                  <ShoppingBag size={16} className="text-slate-400" /> {data.product_requested}
                </div>
              </div>

              <div className="h-px bg-slate-100 my-2" />

              <div className="space-y-1">
                <span className="text-xs text-slate-500 font-medium">Desfecho</span>
                {data.converted ? (
                   <div className="flex items-center gap-2 text-green-600 font-bold bg-green-50 px-3 py-2 rounded-lg border border-green-100">
                     <Award size={18} /> Venda Fechada
                     {data.product_sold && <span className="text-green-800 text-xs font-normal ml-auto">{data.product_sold}</span>}
                   </div>
                ) : (
                   <div className="flex items-center gap-2 text-slate-500 font-medium bg-slate-50 px-3 py-2 rounded-lg border border-slate-100">
                     <div className="w-2 h-2 rounded-full bg-slate-400" /> Não Convertido
                   </div>
                )}
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  );
};