'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { Alert, App, Button, Input, Skeleton, Timeline } from 'antd';
import { Icon } from '../ui/Icon';
import { ApiError } from '../../lib/api';
import type { CrmNote } from '../../lib/leads';
import { fmtDate, relTime } from '../platform/platformFormat';

const MAX_NOTE = 5000;

/** Shared activity composer and timeline for CRM records (leads, contacts, accounts). */
export function RecordActivityTimeline({ recordId, createdLabel, createdDetail, createdAt, loadNotes, addNote, onNoteAdded }: { recordId: string; createdLabel: string; createdDetail?: string | null; createdAt: string; loadNotes: (id: string) => Promise<CrmNote[]>; addNote: (id: string, body: string) => Promise<CrmNote>; onNoteAdded?: () => void }) {
  const { message } = App.useApp();
  const [loaded, setLoaded] = useState<{
    id: string;
    items: CrmNote[];
  } | null>(null);
  const [errorState, setErrorState] = useState<{
    id: string;
    text: string;
  } | null>(null);
  const [text, setText] = useState('');
  const [saving, setSaving] = useState(false);

  const notes = loaded?.id === recordId ? loaded.items : null;
  const error = errorState?.id === recordId ? errorState.text : null;

  const load = useCallback(async () => {
    setErrorState(null);
    try {
      const items = await loadNotes(recordId);
      setLoaded({ id: recordId, items });
    } catch (err) {
      setErrorState({
        id: recordId,
        text: err instanceof ApiError ? err.message : 'Notes could not be loaded.',
      });
    }
  }, [loadNotes, recordId]);

  useEffect(() => {
    let active = true;
    loadNotes(recordId)
      .then((items) => {
        if (active) {
          setErrorState(null);
          setLoaded({ id: recordId, items });
        }
      })
      .catch((err) => {
        if (active) {
          setErrorState({
            id: recordId,
            text: err instanceof ApiError ? err.message : 'Notes could not be loaded.',
          });
        }
      });
    return () => {
      active = false;
    };
  }, [loadNotes, recordId]);

  const submit = async () => {
    const body = text.trim();
    if (!body) return;
    setSaving(true);
    try {
      const note = await addNote(recordId, body);
      setLoaded((prev) => ({
        id: recordId,
        items: [note, ...(prev?.id === recordId ? prev.items : [])],
      }));
      setText('');
      message.success('Note added');
      onNoteAdded?.();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : 'The note could not be saved.');
    } finally {
      setSaving(false);
    }
  };

  const items = [
    ...(notes ?? []).map((n) => ({
      key: n.id,
      icon: <TimelineIcon name="fileText" tone="amber" />,
      content: (
        <div className="pb-1">
          <div className="text-[13.5px] font-semibold text-[var(--tcx-text)]">Note</div>
          <p className="m-0 whitespace-pre-wrap text-[13.5px] text-[var(--tcx-text-2)]">{n.body}</p>
          <div className="text-[12px] text-[var(--tcx-muted)]">
            {n.author?.name ?? 'Former user'}, {relTime(n.createdAt)}
          </div>
        </div>
      ),
    })),
    {
      key: 'created',
      icon: <TimelineIcon name="plus" tone="gray" />,
      content: (
        <div>
          <div className="text-[13.5px] font-semibold text-[var(--tcx-text)]">{createdLabel}</div>
          {createdDetail ? <p className="m-0 text-[13.5px] text-[var(--tcx-text-2)]">{createdDetail}</p> : null}
          <div className="text-[12px] text-[var(--tcx-muted)]">{fmtDate(createdAt)}</div>
        </div>
      ),
    },
  ];

  return (
    <div>
      <div className="rounded-[10px] border border-[var(--tcx-border)] bg-[var(--tcx-surface)]">
        <label htmlFor={`note-${recordId}`} className="sr-only">
          Add a note
        </label>
        <Input.TextArea
          id={`note-${recordId}`}
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Add a note for your team"
          autoSize={{ minRows: 2, maxRows: 8 }}
          maxLength={MAX_NOTE}
          variant="borderless"
          onKeyDown={(e) => {
            if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) void submit();
          }}
        />
      </div>
      <div className="mt-2 mb-4 flex items-center justify-between gap-3">
        <span className="text-[12.5px] text-[var(--tcx-muted)]">Notes are visible to everyone in your organization</span>
        <Button type="primary" size="small" loading={saving} disabled={!text.trim()} onClick={() => void submit()}>
          Add note
        </Button>
      </div>

      {error ? (
        <Alert
          type="error"
          showIcon
          title={error}
          action={
            <Button size="small" onClick={() => void load()}>
              Retry
            </Button>
          }
        />
      ) : notes === null ? (
        <Skeleton active paragraph={{ rows: 3 }} />
      ) : (
        <Timeline items={items} />
      )}
    </div>
  );
}

function TimelineIcon({ name, tone }: { name: 'fileText' | 'plus'; tone: 'amber' | 'gray' }) {
  return (
    <span className={`grid h-7 w-7 place-items-center rounded-full ${tone === 'amber' ? 'bg-[var(--tcx-soft-amber)] text-[var(--tcx-warning)]' : 'bg-[var(--tcx-sunken)] text-[var(--tcx-muted)]'}`}>
      <Icon name={name} size={14} />
    </span>
  );
}
