'use client';

import { useEffect, useState } from 'react';
import { formatPhone, relativeTime } from '@/lib/utils';

interface ContactDetail {
  id: string;
  phone: string;
  name: string | null;
  email: string | null;
  status: string;
  tags: string;
  fields_json: string;
  message_count: number;
  last_contact: string;
  first_contact: string;
  bot_name: string | null;
  assigned_bot_id: string | null;
  closebot_lead_id: string | null;
}

interface Message {
  id: string;
  direction: string;
  source: string;
  body: string;
  created_at: string;
}

interface Props {
  contactId: string;
  onClose: () => void;
  onUpdated: () => void;
}

export function ContactDetailPanel({ contactId, onClose, onUpdated }: Props) {
  const [contact, setContact] = useState<ContactDetail | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDetail = async () => {
      setLoading(true);
      try {
        const res = await fetch(`/api/contacts/${contactId}`);
        if (res.ok) {
          const data = await res.json();
          setContact(data.contact);
          setMessages(data.messages || []);
        }
      } catch (err) {
        console.error('Failed to fetch contact detail:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchDetail();
  }, [contactId]);

  const parseTags = (s: string): string[] => {
    try { const p = JSON.parse(s); return Array.isArray(p) ? p : []; } catch { return []; }
  };

  const parseFields = (s: string): Record<string, string> => {
    try { const p = JSON.parse(s); return typeof p === 'object' && p !== null ? p : {}; } catch { return {}; }
  };

  // Build a conversation summary from recent messages
  const buildSummary = (msgs: Message[]): string[] => {
    if (msgs.length === 0) return ['No messages yet'];
    const summary: string[] = [];
    const inbound = msgs.filter((m) => m.direction === 'inbound').length;
    const outbound = msgs.filter((m) => m.direction === 'outbound').length;
    summary.push(`${inbound} inbound, ${outbound} outbound messages`);
    if (msgs.length > 0) {
      const first = msgs[0];
      summary.push(`First message: ${relativeTime(first.created_at)}`);
    }
    if (msgs.length > 1) {
      const last = msgs[msgs.length - 1];
      summary.push(`Latest message: ${relativeTime(last.created_at)}`);
      const preview = last.body.length > 80 ? last.body.slice(0, 80) + '…' : last.body;
      summary.push(`Last: "${preview}"`);
    }
    return summary;
  };

  if (loading) {
    return (
      <div
        className="w-80 shrink-0 card animate-pulse flex items-center justify-center"
        style={{ minHeight: 400 }}
      >
        <div className="flex flex-col items-center gap-2" style={{ color: 'var(--text-muted)' }}>
          <svg className="animate-spin h-6 w-6" style={{ color: 'var(--accent-cyan)' }} viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
          Loading...
        </div>
      </div>
    );
  }

  if (!contact) {
    return (
      <div className="w-80 shrink-0 card p-6 text-center" style={{ color: 'var(--text-muted)' }}>
        Contact not found
      </div>
    );
  }

  const tags = parseTags(contact.tags);
  const fields = parseFields(contact.fields_json);
  const fieldEntries = Object.entries(fields).filter(([, v]) => v);
  const summary = buildSummary(messages);

  return (
    <div
      className="w-80 shrink-0 card overflow-y-auto animate-in slide-in-from-right"
      style={{ maxHeight: 'calc(100vh - 180px)' }}
    >
      {/* Header */}
      <div
        className="sticky top-0 z-10 px-5 py-4 flex items-center justify-between border-b"
        style={{
          background: 'rgba(30, 41, 59, 0.95)',
          backdropFilter: 'blur(8px)',
          borderColor: 'var(--border)',
        }}
      >
        <h2 className="text-lg font-bold text-white truncate">
          {contact.name || 'Unknown Contact'}
        </h2>
        <button
          onClick={onClose}
          className="p-1 rounded-lg transition-colors hover:bg-white/10"
          style={{ color: 'var(--text-muted)' }}
        >
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div className="p-5 space-y-5">
        {/* Contact Info Fields */}
        <div className="space-y-3">
          {/* Phone */}
          <div className="flex items-center gap-3">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
              style={{ background: 'rgba(34, 211, 238, 0.1)' }}
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" style={{ color: 'var(--accent-cyan)' }}>
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
              </svg>
            </div>
            <div>
              <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Phone</p>
              <p className="text-sm font-medium text-white num">{formatPhone(contact.phone)}</p>
            </div>
          </div>

          {/* Email */}
          <div className="flex items-center gap-3">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
              style={{ background: 'rgba(59, 130, 246, 0.1)' }}
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" style={{ color: 'var(--accent-blue)' }}>
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
            </div>
            <div>
              <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Email</p>
              <p className="text-sm font-medium" style={{ color: contact.email ? 'white' : 'var(--text-muted)' }}>
                {contact.email || 'Not provided'}
              </p>
            </div>
          </div>

          {/* Bot / Company */}
          <div className="flex items-center gap-3">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
              style={{ background: 'rgba(168, 85, 247, 0.1)' }}
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" style={{ color: 'var(--accent-purple)' }}>
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
            </div>
            <div>
              <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Assigned Bot</p>
              <p className="text-sm font-medium" style={{ color: contact.bot_name ? 'white' : 'var(--text-muted)' }}>
                {contact.bot_name || 'Unassigned'}
              </p>
            </div>
          </div>
        </div>

        {/* Tags */}
        {tags.length > 0 && (
          <div>
            <p className="text-xs font-medium mb-2" style={{ color: 'var(--text-muted)' }}>Tags</p>
            <div className="flex flex-wrap gap-1.5">
              {tags.map((tag, i) => (
                <span
                  key={i}
                  className="px-2 py-0.5 rounded-full text-xs font-medium"
                  style={{
                    background: 'rgba(34, 211, 238, 0.1)',
                    color: 'var(--accent-cyan)',
                    border: '1px solid rgba(34, 211, 238, 0.2)',
                  }}
                >
                  {tag}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* Conversation Summary */}
        <div>
          <p className="text-xs font-medium mb-2" style={{ color: 'var(--text-muted)' }}>
            Conversation Summary
          </p>
          <div
            className="rounded-lg p-3 space-y-1.5"
            style={{ background: 'var(--bg-primary)', border: '1px solid var(--border)' }}
          >
            {summary.map((item, i) => (
              <div key={i} className="flex items-start gap-2 text-xs">
                <span className="mt-1.5 w-1.5 h-1.5 rounded-full shrink-0" style={{ background: 'var(--accent-cyan)' }} />
                <span style={{ color: 'var(--text-secondary)' }}>{item}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Field Values Collected */}
        {fieldEntries.length > 0 && (
          <div>
            <p className="text-xs font-medium mb-2" style={{ color: 'var(--text-muted)' }}>
              Field Values Collected
            </p>
            <div
              className="rounded-lg overflow-hidden"
              style={{ border: '1px solid var(--border)' }}
            >
              <table className="w-full text-xs">
                <thead>
                  <tr style={{ background: 'var(--bg-primary)' }}>
                    <th className="text-left px-3 py-2 font-medium" style={{ color: 'var(--text-muted)' }}>Field</th>
                    <th className="text-left px-3 py-2 font-medium" style={{ color: 'var(--text-muted)' }}>Value</th>
                  </tr>
                </thead>
                <tbody>
                  {fieldEntries.map(([key, val], i) => (
                    <tr
                      key={key}
                      style={{
                        borderTop: i > 0 ? '1px solid var(--border)' : undefined,
                        background: 'var(--bg-tertiary)',
                      }}
                    >
                      <td className="px-3 py-2 font-medium capitalize" style={{ color: 'var(--text-secondary)' }}>
                        {key.replace(/_/g, ' ')}
                      </td>
                      <td className="px-3 py-2 text-white">{val}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Action Buttons */}
        <div className="space-y-2 pt-2">
          <a
            href={`/conversations?contact=${contact.id}`}
            className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors"
            style={{
              background: 'var(--accent-cyan)',
              color: '#0f1729',
            }}
            onMouseEnter={(e) => (e.currentTarget.style.opacity = '0.9')}
            onMouseLeave={(e) => (e.currentTarget.style.opacity = '1')}
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
            </svg>
            View Full History
          </a>
          <button
            onClick={() => {
              // Navigate to conversations with this contact
              window.location.href = `/conversations?contact=${contact.id}&send=true`;
            }}
            className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors"
            style={{
              background: 'transparent',
              color: 'var(--accent-cyan)',
              border: '1px solid var(--accent-cyan)',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(34, 211, 238, 0.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
            }}
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
            Send Message
          </button>
        </div>

        {/* Footer meta */}
        <div className="text-xs pt-2 space-y-1" style={{ color: 'var(--text-muted)' }}>
          <p>First contact: {contact.first_contact ? relativeTime(contact.first_contact) : '—'}</p>
          <p>Total messages: {contact.message_count}</p>
          {contact.closebot_lead_id && <p>Lead ID: {contact.closebot_lead_id}</p>}
        </div>
      </div>
    </div>
  );
}
