"use client";

import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogPortal } from "@/components/ui/dialog";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Loader2, X } from "lucide-react";
import { useSession } from "next-auth/react";
import * as React from "react";

// Custom DialogOverlay to override the default black background
const DialogOverlay = React.forwardRef<
  React.ElementRef<typeof DialogPrimitive.Overlay>,
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
  <DialogPrimitive.Overlay
    ref={ref}
    className={cn(
      "fixed inset-0 z-50 bg-black/40 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
      className
    )}
    {...props}
  />
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;

interface NotesDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function NotesDialog({ open, onOpenChange }: NotesDialogProps) {
  const { data: session } = useSession();
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState("");

  const handleSave = async () => {
    if (!title.trim()) {
      setError("Please enter a title for your note");
      return;
    }

    if (!content.trim()) {
      setError("Please enter content for your note");
      return;
    }

    try {
      setIsSaving(true);
      setError("");

      // Construct API payload with lowercase folder name (always "notes" for quick notes)
      // Note: The API will construct the full path from folder and title
      const payload = {
        title: title,
        content: content,
        folder: "notes", // Always save to Notes folder (lowercase for consistency)
        mime: "text/markdown"
      };
      
      // Use direct storage API endpoint
      const response = await fetch('/api/storage/files', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        console.error('Failed to save note:', errorText);
        throw new Error('Failed to save note');
      }
      
      // Invalidate cache and trigger refresh
      try {
        // Clear localStorage cache for notes
        const userId = session?.user?.id;
        if (userId) {
          const cacheKey = `${userId}-notes`;
          localStorage.removeItem(`notes-cache-${cacheKey}`);
        }
        
        // Dispatch custom event to notify pages to refresh
        window.dispatchEvent(new CustomEvent('note-saved', { 
          detail: { folder: 'notes' } 
        }));
      } catch (cacheError) {
        console.error('Error clearing cache:', cacheError);
      }
      
      // Reset form and close dialog
      setTitle("");
      setContent("");
      onOpenChange(false);
      
    } catch (err) {
      console.error('Error saving note:', err);
      setError("Failed to save your note. Please try again.");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogPortal>
        <DialogOverlay />
        <DialogContent className="sm:max-w-[500px] bg-white border-gray-200">
          <DialogHeader>
            <DialogTitle className="text-gray-900">Quick Note</DialogTitle>
          </DialogHeader>
          
          <div className="grid gap-4 py-4">
            {error && (
              <div className="bg-red-50 text-red-500 p-2 rounded-md text-sm">
                {error}
              </div>
            )}
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Input
                id="title"
                placeholder="Note title"
                className="col-span-4 text-gray-800 bg-white border-gray-300 placeholder-gray-500"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                disabled={isSaving}
              />
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Textarea
                id="content"
                placeholder="What's on your mind?"
                className="col-span-4 text-gray-800 bg-white border-gray-300 placeholder-gray-500"
                rows={10}
                value={content}
                onChange={(e) => setContent(e.target.value)}
                disabled={isSaving}
              />
            </div>
          </div>
          
          <DialogFooter>
            <Button 
              variant="destructive" 
              onClick={() => onOpenChange(false)} 
              disabled={isSaving}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              Cancel
            </Button>
            <Button 
              onClick={handleSave} 
              disabled={isSaving}
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              {isSaving ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                "Save Note"
              )}
            </Button>
          </DialogFooter>
          <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
            <X className="h-4 w-4 text-gray-500" />
            <span className="sr-only">Close</span>
          </DialogPrimitive.Close>
        </DialogContent>
      </DialogPortal>
    </Dialog>
  );
} 