'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useMemo, useState } from 'react';

type Props = {
  contact: {
    id: string;
    name: string;
    email: string | null;
    phoneNumber: string;
    company: string | null;
    status: 'Active' | 'Inactive';
    tags: string[];
    location: string;
    lastSeenLabel: string;
    isBlacklisted: boolean;
    avatarInitials: string;
    notes: Array<{
      id: string;
      author: string;
      dateLabel: string;
      body: string;
      emphasized: boolean;
    }>;
    history: Array<{
      id: string;
      type: string;
      title: string;
      at: string;
      summary: string;
      status: string;
      errorReason: string | null;
    }>;
  };
};

function formatTimelineDate(value: string) {
  const date = new Date(value);
  return date.toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: true,
    timeZone: 'UTC',
  });
}

export function ContactDetailBoard({ contact }: Props) {
  const router = useRouter();
  const [tab, setTab] = useState<'all' | 'messages' | 'system'>('all');
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form, setForm] = useState({
    name: contact.name,
    phoneNumber: contact.phoneNumber,
    email: contact.email || '',
    company: contact.company || '',
    notes: contact.notes.map((note) => note.body).join('\n'),
    isBlacklisted: contact.isBlacklisted,
  });

  const filteredHistory = useMemo(() => {
    if (tab === 'all') return contact.history;
    if (tab === 'messages') return contact.history.filter((item) => item.type === 'message' || item.type === 'inbound');
    return contact.history.filter((item) => item.type !== 'message' && item.type !== 'inbound');
  }, [contact.history, tab]);

  return (
    <div className="contact-detail-page">
      <nav className="contact-detail-breadcrumb">
        <Link href="/dashboard/contacts">Contacts</Link>
        <span className="material-symbols-outlined">chevron_right</span>
        <span>{contact.name}</span>
      </nav>

      <section className="contact-detail-hero">
        <div className="contact-detail-hero-main">
          <div className="contact-detail-hero-avatar">
            <span>{contact.avatarInitials}</span>
            <i />
          </div>
          <div>
            <div className="contact-detail-hero-title">
              <h1>{contact.name}</h1>
              <span>ID: {contact.id.slice(0, 6).toUpperCase()}</span>
            </div>
            <p>{contact.status} Customer • Last seen {contact.lastSeenLabel}</p>
          </div>
        </div>
        <div className="contact-detail-hero-actions">
          <button type="button" className="contacts-secondary-button" onClick={() => setIsEditing(true)}>
            <span className="material-symbols-outlined">edit</span>
            Edit Contact
          </button>
          <Link href="/dashboard/conversations" className="contacts-primary-button">
            <span className="material-symbols-outlined">chat</span>
            Message
          </Link>
          <button
            type="button"
            className="contact-detail-danger-icon"
            onClick={async () => {
              try {
                setError(null);
                const response = await fetch(`/api/contacts/${contact.id}`, {
                  method: 'PATCH',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ isBlacklisted: !form.isBlacklisted }),
                });
                const payload = await response.json();
                if (!response.ok) {
                  throw new Error(typeof payload?.message === 'string' ? payload.message : 'Failed to update contact');
                }
                router.refresh();
              } catch (actionError) {
                setError(actionError instanceof Error ? actionError.message : 'Failed to update contact');
              }
            }}
          >
            <span className="material-symbols-outlined">block</span>
          </button>
        </div>
      </section>

      {error ? <p className="contacts-form-error">{error}</p> : null}

      <section className="contact-detail-grid">
        <aside className="contact-detail-sidebar">
          <article className="contact-detail-card">
            <h2><span className="material-symbols-outlined">info</span>Contact Information</h2>
            <div className="contact-detail-info-list">
              <div>
                <label>Phone Number</label>
                <div className="contact-detail-info-row">
                  <strong>{contact.phoneNumber}</strong>
                  <button type="button" className="contacts-icon-button" onClick={() => navigator.clipboard.writeText(contact.phoneNumber)}>
                    <span className="material-symbols-outlined">content_copy</span>
                  </button>
                </div>
              </div>
              <div>
                <label>Email Address</label>
                <strong>{contact.email || 'No email on file'}</strong>
              </div>
              <div>
                <label>Location</label>
                <strong>{contact.location}</strong>
              </div>
              <div>
                <label>Tags</label>
                <div className="contacts-tags-inline is-wrap">
                  {contact.tags.map((tag) => (
                    <span key={tag} className="contacts-tag-chip">
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          </article>

          <article className="contact-detail-card">
            <div className="contact-detail-card-head">
              <h2><span className="material-symbols-outlined">sticky_note_2</span>Internal Notes</h2>
              <button type="button" onClick={() => setIsEditing(true)}>Add Note</button>
            </div>
            <div className="contact-detail-notes">
              {contact.notes.map((note) => (
                <div key={note.id} className={note.emphasized ? 'contact-note-card is-emphasized' : 'contact-note-card'}>
                  <p>{note.body}</p>
                  <div>
                    <span>- {note.author}</span>
                    <span>{note.dateLabel}</span>
                  </div>
                </div>
              ))}
            </div>
          </article>
        </aside>

        <section className="contact-detail-history-card">
          <div className="contact-detail-card-head">
            <h2><span className="material-symbols-outlined">history</span>Interaction History</h2>
            <div className="contact-detail-tabs">
              <button type="button" className={tab === 'all' ? 'is-active' : ''} onClick={() => setTab('all')}>All Activity</button>
              <button type="button" className={tab === 'messages' ? 'is-active' : ''} onClick={() => setTab('messages')}>Messages</button>
              <button type="button" className={tab === 'system' ? 'is-active' : ''} onClick={() => setTab('system')}>System</button>
            </div>
          </div>

          <div className="contact-history-timeline">
            {filteredHistory.map((item) => (
              <div key={item.id} className="contact-history-item">
                <div className="contact-history-icon">
                  <span className="material-symbols-outlined">
                    {item.type === 'message' ? 'chat' : item.type === 'inbound' ? 'call_received' : item.type === 'tag' ? 'sell' : 'person_pin'}
                  </span>
                </div>
                <div className="contact-history-body">
                  <div className="contact-history-title">
                    <strong>{item.title}</strong>
                    <span>• {formatTimelineDate(item.at)}</span>
                  </div>
                  <p>{item.summary}</p>
                  {item.errorReason ? <small>{item.errorReason}</small> : null}
                </div>
              </div>
            ))}
          </div>
        </section>
      </section>

      {isEditing ? (
        <div className="contacts-modal-backdrop" onClick={() => setIsEditing(false)}>
          <div className="contacts-modal-card" onClick={(event) => event.stopPropagation()}>
            <div className="contacts-modal-head">
              <div>
                <p>Edit Contact</p>
                <h2>Update contact profile</h2>
              </div>
              <button type="button" className="contacts-icon-button" onClick={() => setIsEditing(false)}>
                <span className="material-symbols-outlined">close</span>
              </button>
            </div>

            <form
              className="contacts-form-grid"
              onSubmit={async (event) => {
                event.preventDefault();
                try {
                  setError(null);
                  setIsSaving(true);
                  const response = await fetch(`/api/contacts/${contact.id}`, {
                    method: 'PATCH',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(form),
                  });
                  const payload = await response.json();
                  if (!response.ok) {
                    throw new Error(typeof payload?.message === 'string' ? payload.message : 'Failed to update contact');
                  }
                  setIsEditing(false);
                  router.refresh();
                } catch (submissionError) {
                  setError(submissionError instanceof Error ? submissionError.message : 'Failed to update contact');
                } finally {
                  setIsSaving(false);
                }
              }}
            >
              <label className="contacts-form-field">
                <span>Full Name</span>
                <input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} />
              </label>
              <label className="contacts-form-field">
                <span>Phone Number</span>
                <input value={form.phoneNumber} onChange={(event) => setForm((current) => ({ ...current, phoneNumber: event.target.value }))} />
              </label>
              <label className="contacts-form-field">
                <span>Email Address</span>
                <input value={form.email} onChange={(event) => setForm((current) => ({ ...current, email: event.target.value }))} />
              </label>
              <label className="contacts-form-field">
                <span>Company</span>
                <input value={form.company} onChange={(event) => setForm((current) => ({ ...current, company: event.target.value }))} />
              </label>
              <label className="contacts-form-field is-full">
                <span>Notes</span>
                <textarea rows={5} value={form.notes} onChange={(event) => setForm((current) => ({ ...current, notes: event.target.value }))} />
              </label>
              <label className="contacts-checkbox-row is-full">
                <input
                  type="checkbox"
                  checked={form.isBlacklisted}
                  onChange={(event) => setForm((current) => ({ ...current, isBlacklisted: event.target.checked }))}
                />
                <span>Mark this contact as inactive / blocked</span>
              </label>
              <div className="contacts-form-actions">
                <button type="button" className="contacts-secondary-button" onClick={() => setIsEditing(false)}>
                  Cancel
                </button>
                <button type="button" className="contact-detail-delete-button" disabled={isDeleting} onClick={async () => {
                  if (!window.confirm(`Delete contact "${contact.name}"?`)) return;
                  try {
                    setError(null);
                    setIsDeleting(true);
                    const response = await fetch(`/api/contacts/${contact.id}`, { method: 'DELETE' });
                    const payload = await response.json();
                    if (!response.ok) {
                      throw new Error(typeof payload?.message === 'string' ? payload.message : 'Failed to delete contact');
                    }
                    router.push('/dashboard/contacts');
                    router.refresh();
                  } catch (deleteError) {
                    setError(deleteError instanceof Error ? deleteError.message : 'Failed to delete contact');
                  } finally {
                    setIsDeleting(false);
                  }
                }}>
                  <span className="material-symbols-outlined">delete</span>
                  {isDeleting ? 'Deleting...' : 'Delete'}
                </button>
                <button type="submit" className="contacts-primary-button" disabled={isSaving}>
                  <span className="material-symbols-outlined">save</span>
                  {isSaving ? 'Saving...' : 'Save Changes'}
                </button>
              </div>
            </form>
          </div>
        </div>
      ) : null}
    </div>
  );
}
