'use client';

import { useState, useEffect, useCallback } from 'react';
import { X, Trash2, MessageSquarePlus, Loader2 } from 'lucide-react';
import { clsx } from 'clsx';
import type { Memory, MemoryComment } from '@/lib/types';
import { listComments, createComment, deleteMemory } from '@/lib/api';
import { ConfirmationModal } from './confirmation-modal';
import { TagEditor } from './tag-editor';
import { useToast } from './toast';

function statusColor(status: string): string {
  switch (status) {
    case 'active':
      return '#3fb950';
    case 'fading':
      return '#d29922';
    case 'archived':
      return '#8b949e';
    default:
      return '#8b949e';
  }
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });
}

function sourceLabel(source: string): string {
  switch (source) {
    case 'conversation':
      return 'Learned';
    case 'observation':
      return 'Observed';
    case 'task':
      return 'Recalled';
    case 'upload':
      return 'Uploaded';
    default:
      return source.charAt(0).toUpperCase() + source.slice(1);
  }
}

interface MemoryDetailPanelProps {
  memory: Memory | null;
  onClose: () => void;
  onMutate?: () => void;
}

export function MemoryDetailPanel({
  memory,
  onClose,
  onMutate,
}: MemoryDetailPanelProps) {
  const [commentText, setCommentText] = useState('');
  const [comments, setComments] = useState<MemoryComment[]>([]);
  const [loadingComments, setLoadingComments] = useState(false);
  const [submittingComment, setSubmittingComment] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const { showToast } = useToast();

  // Load comments when memory changes
  useEffect(() => {
    if (!memory) {
      setComments([]);
      return;
    }
    let cancelled = false;
    setLoadingComments(true);

    const parts = memory.vaultFullName.split('/');
    if (parts.length < 2) {
      setLoadingComments(false);
      return;
    }
    const owner = parts[0];
    const repo = parts.slice(1).join('/');

    listComments(owner, repo, memory.id).then((data) => {
      if (!cancelled && data && Array.isArray(data)) {
        setComments(
          data.map((c: any) => ({
            id: c.id,
            author: c.user?.login || 'unknown',
            content: c.body || '',
            createdAt: c.created_at,
          }))
        );
      }
      if (!cancelled) setLoadingComments(false);
    }).catch(() => {
      if (!cancelled) setLoadingComments(false);
    });

    return () => { cancelled = true; };
  }, [memory?.id, memory?.vaultFullName]);

  const handleEscape = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    },
    [onClose]
  );

  useEffect(() => {
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [handleEscape]);

  const handleSubmitComment = useCallback(async () => {
    if (!memory || !commentText.trim()) return;
    setSubmittingComment(true);
    const parts = memory.vaultFullName.split('/');
    if (parts.length < 2) return;
    const owner = parts[0];
    const repo = parts.slice(1).join('/');

    try {
      const result = await createComment(owner, repo, memory.id, commentText.trim());
      if (result) {
        showToast('Comment added', 'success');
        setCommentText('');
        // Refresh comments
        const data = await listComments(owner, repo, memory.id);
        if (data && Array.isArray(data)) {
          setComments(
            data.map((c: any) => ({
              id: c.id,
              author: c.user?.login || 'unknown',
              content: c.body || '',
              createdAt: c.created_at,
            }))
          );
        }
      } else {
        showToast('Failed to add comment', 'error');
      }
    } catch {
      showToast('Failed to add comment', 'error');
    } finally {
      setSubmittingComment(false);
    }
  }, [memory, commentText, showToast]);

  const handleDelete = useCallback(async () => {
    if (!memory) return;
    setDeleting(true);
    try {
      const success = await deleteMemory(memory.vaultFullName, memory.id);
      if (success) {
        showToast('Memory deleted', 'success');
        setShowDeleteConfirm(false);
        onClose();
        onMutate?.();
      } else {
        showToast('Failed to delete memory', 'error');
      }
    } catch {
      showToast('Failed to delete memory', 'error');
    } finally {
      setDeleting(false);
    }
  }, [memory, showToast, onClose, onMutate]);

  if (!memory) return null;

  return (
    <>
      <div
        className={clsx(
          'fixed top-0 right-0 h-screen w-[400px] bg-surface-elevated border-l border-border z-30 flex flex-col transition-transform duration-200 ease-in-out',
          memory ? 'translate-x-0' : 'translate-x-full'
        )}
      >
        {memory && (
          <>
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-border">
              <span className="text-sm text-memory font-medium">Memory Detail</span>
              <button
                onClick={onClose}
                className="p-1 rounded-md hover:bg-surface text-text-muted hover:text-text-primary transition-colors"
                aria-label="Close panel"
              >
                <X size={18} />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-4 space-y-5">
              {/* Title */}
              <h2 className="text-lg font-semibold text-text-primary">{memory.title}</h2>

              {/* Importance bar + Status */}
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <span className="text-xs text-text-muted">Importance</span>
                  <div className="w-20 h-1.5 rounded-full bg-border overflow-hidden">
                    <div
                      className="h-full rounded-full bg-memory transition-all"
                      style={{ width: `${memory.importance * 100}%` }}
                    />
                  </div>
                  <span className="text-xs text-text-muted">
                    {memory.importance.toFixed(1)}
                  </span>
                </div>
                <span
                  className={clsx(
                    'text-xs px-2 py-0.5 rounded-full font-medium',
                    memory.status === 'fading' && 'animate-pulse'
                  )}
                  style={{
                    backgroundColor: statusColor(memory.status) + '20',
                    color: statusColor(memory.status),
                  }}
                >
                  {memory.status.charAt(0).toUpperCase() + memory.status.slice(1)}
                </span>
              </div>

              {/* Content */}
              <div>
                <h3 className="text-xs uppercase tracking-wider text-text-muted mb-2">Content</h3>
                <div className="text-sm text-text-secondary leading-relaxed whitespace-pre-wrap">
                  {memory.content}
                </div>
              </div>

              {/* Tags */}
              <div>
                <h3 className="text-xs uppercase tracking-wider text-text-muted mb-2">Tags</h3>
                <TagEditor
                  tags={memory.tags}
                  vaultFullName={memory.vaultFullName}
                  issueNumber={memory.id}
                  onTagsChanged={() => onMutate?.()}
                />
              </div>

              {/* Provenance */}
              <div>
                <h3 className="text-xs uppercase tracking-wider text-text-muted mb-2">
                  Provenance
                </h3>
                <div className="space-y-1.5 text-sm">
                  <div className="flex justify-between">
                    <span className="text-text-muted">Source</span>
                    <span className="text-text-secondary">{sourceLabel(memory.source)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-text-muted">Created</span>
                    <span className="text-text-secondary">{formatDate(memory.createdAt)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-text-muted">Updated</span>
                    <span className="text-text-secondary">{formatDate(memory.updatedAt)}</span>
                  </div>
                </div>
              </div>

              {/* Comments */}
              <div>
                <h3 className="text-xs uppercase tracking-wider text-text-muted mb-2">
                  Comments ({loadingComments ? '...' : comments.length})
                </h3>
                {loadingComments ? (
                  <div className="flex items-center gap-2 py-3">
                    <Loader2 size={14} className="text-text-muted animate-spin" />
                    <span className="text-sm text-text-muted">Loading comments...</span>
                  </div>
                ) : comments.length > 0 ? (
                  <div className="space-y-3">
                    {comments.map((comment) => (
                      <div key={comment.id} className="p-3 rounded-lg bg-surface border border-border-light">
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-xs font-medium text-text-primary">{comment.author}</span>
                          <span className="text-[11px] text-text-muted">{formatDate(comment.createdAt)}</span>
                        </div>
                        <p className="text-sm text-text-secondary">{comment.content}</p>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-text-muted">No comments yet.</p>
                )}

                {/* Add comment */}
                <div className="mt-3 flex gap-2">
                  <input
                    type="text"
                    placeholder="Add a comment..."
                    value={commentText}
                    onChange={(e) => setCommentText(e.target.value)}
                    className="flex-1 px-3 py-1.5 text-sm rounded-md border border-border bg-surface text-text-primary placeholder:text-text-muted focus:outline-none focus:border-memory transition-colors"
                    disabled={submittingComment}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && commentText.trim()) {
                        handleSubmitComment();
                      }
                    }}
                  />
                  <button
                    onClick={handleSubmitComment}
                    disabled={!commentText.trim() || submittingComment}
                    className={clsx(
                      'p-1.5 rounded-md border border-border transition-colors',
                      commentText.trim() && !submittingComment
                        ? 'text-text-secondary hover:text-memory hover:border-memory'
                        : 'text-text-muted cursor-not-allowed'
                    )}
                    aria-label="Add comment"
                  >
                    {submittingComment ? (
                      <Loader2 size={16} className="animate-spin" />
                    ) : (
                      <MessageSquarePlus size={16} />
                    )}
                  </button>
                </div>
              </div>
            </div>

            {/* Actions */}
            <div className="border-t border-border p-4 flex gap-2">
              <button
                onClick={() => setShowDeleteConfirm(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border border-border text-error hover:bg-surface transition-colors"
              >
                <Trash2 size={14} />
                Delete
              </button>
            </div>
          </>
        )}
      </div>

      <ConfirmationModal
        open={showDeleteConfirm}
        title="Delete Memory"
        description={`Are you sure you want to delete "${memory?.title}"? This will close the underlying issue.`}
        confirmLabel={deleting ? 'Deleting...' : 'Delete'}
        onConfirm={handleDelete}
        onCancel={() => setShowDeleteConfirm(false)}
      />
    </>
  );
}
