'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

interface SourceMessage {
  id: string;
  content: string;
  senderName: string | null;
  createdAt: string;
}

interface Draft {
  id: string;
  type: 'EVENT' | 'SEVA_TASK' | 'FAQ_ITEM';
  status: string;
  proposedJson: Record<string, any>;
  confidence: number | null;
  createdAt: string;
  sourceMessage: SourceMessage;
}

const TYPE_LABEL: Record<Draft['type'], string> = {
  EVENT: 'Event',
  SEVA_TASK: 'Seva Task',
  FAQ_ITEM: 'FAQ',
};

const TYPE_COLOR: Record<Draft['type'], string> = {
  EVENT: 'bg-indigo-50 text-indigo-700 border-indigo-200',
  SEVA_TASK: 'bg-green-50 text-green-700 border-green-200',
  FAQ_ITEM: 'bg-amber-50 text-amber-700 border-amber-200',
};

function ProposedPreview({ type, data }: { type: Draft['type']; data: Record<string, any> }) {
  if (type === 'EVENT') {
    return (
      <div className="space-y-1 text-sm">
        <p><span className="font-medium text-gray-700">Title:</span> {data.title ?? '—'}</p>
        {data.date && <p><span className="font-medium text-gray-700">Date:</span> {data.date} {data.time ?? ''}</p>}
        {data.location && <p><span className="font-medium text-gray-700">Location:</span> {data.location}</p>}
        {data.description && <p><span className="font-medium text-gray-700">Description:</span> {data.description}</p>}
        {data.rsvpNeeded && <p className="text-indigo-600 text-xs">RSVP required</p>}
        {data.sevaActionItems?.length > 0 && (
          <p className="text-green-700 text-xs">+{data.sevaActionItems.length} seva task(s) will also be created</p>
        )}
      </div>
    );
  }

  if (type === 'SEVA_TASK') {
    return (
      <div className="space-y-1 text-sm">
        <p><span className="font-medium text-gray-700">Title:</span> {data.title ?? '—'}</p>
        {data.parentEventTitle && <p><span className="font-medium text-gray-700">Event:</span> {data.parentEventTitle}</p>}
        {data.slots && <p><span className="font-medium text-gray-700">Slots:</span> {data.slots}</p>}
        {data.skills?.length > 0 && <p><span className="font-medium text-gray-700">Skills:</span> {data.skills.join(', ')}</p>}
      </div>
    );
  }

  return (
    <div className="space-y-1 text-sm">
      <p><span className="font-medium text-gray-700">Q:</span> {data.question ?? '—'}</p>
      <p><span className="font-medium text-gray-700">A:</span> {data.answer ?? '—'}</p>
      {data.tags?.length > 0 && (
        <div className="flex gap-1 flex-wrap mt-1">
          {data.tags.map((t: string) => (
            <span key={t} className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">{t}</span>
          ))}
        </div>
      )}
    </div>
  );
}

export function DraftCard({ draft }: { draft: Draft }) {
  const router = useRouter();
  const [loading, setLoading] = useState<'approve' | 'reject' | null>(null);

  async function act(action: 'approve' | 'reject') {
    setLoading(action);
    try {
      await fetch(`/api/admin/drafts/${draft.id}/${action}`, { method: 'POST' });
      router.refresh();
    } finally {
      setLoading(null);
    }
  }

  const confidence = draft.confidence != null ? Math.round(draft.confidence * 100) : null;

  return (
    <div className="bg-white border border-gray-200 rounded-xl p-5 space-y-4">
      <div className="flex items-start justify-between gap-3">
        <span className={`text-xs font-semibold px-2.5 py-1 rounded-full border ${TYPE_COLOR[draft.type]}`}>
          {TYPE_LABEL[draft.type]}
        </span>
        {confidence != null && (
          <span className="text-xs text-gray-400">{confidence}% confidence</span>
        )}
      </div>

      {/* Source message */}
      <div className="bg-gray-50 rounded-lg p-3 border border-gray-100">
        <p className="text-xs font-medium text-gray-500 mb-1">
          Source message{draft.sourceMessage.senderName ? ` — ${draft.sourceMessage.senderName}` : ''}
        </p>
        <p className="text-sm text-gray-700 line-clamp-3">{draft.sourceMessage.content}</p>
      </div>

      {/* AI proposed content */}
      <div>
        <p className="text-xs font-medium text-gray-500 mb-2">AI proposed</p>
        <ProposedPreview type={draft.type} data={draft.proposedJson} />
      </div>

      {/* Actions */}
      <div className="flex gap-2 pt-1">
        <button
          onClick={() => act('approve')}
          disabled={loading !== null}
          className="flex-1 py-2 text-sm font-medium rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 disabled:opacity-50 transition-colors"
        >
          {loading === 'approve' ? 'Approving…' : 'Approve'}
        </button>
        <button
          onClick={() => act('reject')}
          disabled={loading !== null}
          className="flex-1 py-2 text-sm font-medium rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 disabled:opacity-50 transition-colors"
        >
          {loading === 'reject' ? 'Rejecting…' : 'Reject'}
        </button>
      </div>
    </div>
  );
}
