'use client';

import { useState, useEffect } from 'react';
import { Copy, Check, X, Trash2 } from 'lucide-react';
import { useHistoryStore } from '@/lib/store/history-store';
import { DraftContent } from '@/components/features/draft/DraftContent';
import { CopySuccessToast } from '@/components/features/feedback/CopySuccessToast';
import { useChatStore } from '@/store/use-chat';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from '@/components/ui/sheet';
import { DeleteConfirmDialog } from './DeleteConfirmDialog';

/**
 * HistoryDetailSheet Component
 *
 * Story 3.1: Full draft view from history feed
 *
 * Reuses:
 * - Sheet component from DraftViewSheet (Story 2.2)
 * - DraftContent component (Story 2.2)
 * - CopyButton functionality (Story 2.4)
 * - Delete functionality (Story 3.2.1)
 *
 * Features:
 * - Displays full draft with Merriweather font
 * - Copy button for clipboard export
 * - Close button
 * - Delete button
 * - Swipe-to-dismiss support (via Sheet)
 *
 * Architecture Compliance:
 * - Uses atomic selectors from HistoryStore
 * - Reuses ChatStore's copyDraftToClipboard action
 */
export function HistoryDetailSheet() {
  const selectedDraft = useHistoryStore((s) => s.selectedDraft);
  const closeDetail = useHistoryStore((s) => s.closeDetail);
  const deleteDraft = useHistoryStore((s) => s.deleteDraft);

  // Dialog state
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // Toast state
  const [toastShow, setToastShow] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // Fix: Reset toast when opening a new draft
  useEffect(() => {
    setToastShow(false);
  }, [selectedDraft]);

  const showCopyToast = (message: string = 'Copied to clipboard!') => {
    setToastMessage(message);
    setToastShow(true);
  };

  // Placeholder copy function since ChatStore might not have it exposed exactly this way yet
  // or we need to implement it here.
  const handleCopy = async () => {
    if (selectedDraft) {
      await navigator.clipboard.writeText(selectedDraft.content);
      showCopyToast();
    }
  };

  const handleDelete = async () => {
    if (selectedDraft) {
      const success = await deleteDraft(selectedDraft.id);
      if (success) {
        setShowDeleteDialog(false);
        showCopyToast('Post deleted successfully');
        closeDetail(); // Close sheet on delete
      } else {
        setShowDeleteDialog(false);
        showCopyToast('Failed to delete post');
      }
    }
  };

  if (!selectedDraft) {
    return null;
  }

  return (
    <>
      <Sheet open={!!selectedDraft} onOpenChange={(open) => !open && closeDetail()}>
        <SheetContent side="right" className="w-full sm:max-w-xl overflow-y-auto p-0">
          <SheetHeader className="sr-only">
            <SheetTitle>Draft Details</SheetTitle>
            <SheetDescription>View your saved draft details</SheetDescription>
          </SheetHeader>
          <div className="p-6">
            <DraftContent draft={selectedDraft} />
          </div>

          {/* Footer with copy, delete and close buttons */}
          <nav className="sticky bottom-0 flex gap-3 p-4 bg-white border-t border-slate-200 mt-auto">
            {/* Delete button (Story 3.2.1) */}
            <button
              onClick={() => setShowDeleteDialog(true)}
              type="button"
              className="min-h-[44px] px-4 py-3 border border-destructive text-destructive rounded-md hover:bg-destructive/10 transition-colors flex items-center justify-center gap-2"
              aria-label="Delete this draft"
            >
              <Trash2 className="w-5 h-5" aria-hidden="true" />
              <span className="sr-only">Delete</span>
            </button>

            {/* Copy button */}
            <button
              onClick={handleCopy}
              type="button"
              className="flex-1 min-h-[44px] px-4 py-3 border border-slate-300 rounded-md text-slate-700 hover:bg-slate-50 transition-colors flex items-center justify-center gap-2"
              aria-label="Copy to clipboard"
            >
              <Copy className="w-5 h-5" aria-hidden="true" />
              <span>Copy</span>
            </button>

            {/* Close button */}
            <button
              onClick={closeDetail}
              type="button"
              className="min-h-[44px] px-4 py-3 bg-slate-800 text-white rounded-md hover:bg-slate-700 transition-colors flex items-center justify-center gap-2"
              aria-label="Close"
            >
              <X className="w-5 h-5" aria-hidden="true" />
              <span>Close</span>
            </button>
          </nav>
        </SheetContent>
      </Sheet>

      {/* Delete Confirmation Dialog */}
      <DeleteConfirmDialog
        open={showDeleteDialog}
        onOpenChange={setShowDeleteDialog}
        onConfirm={handleDelete}
        draftTitle={selectedDraft.title}
      />

      {/* Toast for feedack */}
      <CopySuccessToast
        show={toastShow}
        message={toastMessage}
        onClose={() => setToastShow(false)}
      />
    </>
  );
}
