import { useEffect, useState, useRef } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Save, Pencil, X } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

interface Props {
  appointmentId: number;
  enabled: boolean;
}

export function AppointmentProcedureNotes({
  appointmentId,
  enabled,
}: Props) {
  const { toast } = useToast();

  const [notes, setNotes] = useState("");
  const [originalNotes, setOriginalNotes] = useState("");
  const [isEditing, setIsEditing] = useState(false);

  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // -------------------------
  // Load procedure notes
  // -------------------------
  useQuery({
    queryKey: ["appointment-procedure-notes", appointmentId],
    enabled: enabled && !!appointmentId,
    queryFn: async () => {
      const res = await apiRequest(
        "GET",
        `/api/appointments/${appointmentId}/procedure-notes`
      );
      if (!res.ok) throw new Error("Failed to load notes");

      const data = await res.json();
      const value = data.procedureNotes ?? "";

      setNotes(value);
      setOriginalNotes(value);
      setIsEditing(false);

      return data;
    },
  });

  // -------------------------
  // Save procedure notes
  // -------------------------
  const saveMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest(
        "PUT",
        `/api/appointments/${appointmentId}/procedure-notes`,
        { procedureNotes: notes }
      );
      if (!res.ok) throw new Error("Failed to save notes");
    },
    onSuccess: () => {
      toast({ title: "Procedure notes saved" });
      setOriginalNotes(notes);
      setIsEditing(false);

      queryClient.invalidateQueries({
        queryKey: ["appointment-procedure-notes", appointmentId],
      });
    },
    onError: (err: any) => {
      toast({
        title: "Error",
        description: err.message ?? "Failed to save notes",
        variant: "destructive",
      });
    },
  });

  // Autofocus textarea when editing
  useEffect(() => {
    if (isEditing) {
      textareaRef.current?.focus();
    }
  }, [isEditing]);

  const handleCancel = () => {
    setNotes(originalNotes);
    setIsEditing(false);
  };

  const hasChanges = notes !== originalNotes;

  return (
    <div className="border rounded-lg p-4 bg-muted/20 space-y-2">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="text-sm font-medium">Procedure Notes</div>

        {!isEditing ? (
          <Button
            size="sm"
            variant="outline"
            onClick={() => setIsEditing(true)}
          >
            <Pencil className="h-4 w-4 mr-1" />
            Edit
          </Button>
        ) : (
          <div className="flex gap-2">
            <Button
              size="sm"
              variant="ghost"
              onClick={handleCancel}
            >
              <X className="h-4 w-4 mr-1" />
              Cancel
            </Button>

            <Button
              size="sm"
              onClick={() => saveMutation.mutate()}
              disabled={saveMutation.isPending || !hasChanges}
            >
              <Save className="h-4 w-4 mr-1" />
              Save
            </Button>
          </div>
        )}
      </div>

      {/* Textarea */}
      <textarea
        ref={textareaRef}
        className={`w-full min-h-[90px] rounded-md border px-3 py-2 text-sm transition
          focus:outline-none focus:ring-2 focus:ring-ring
          ${
            isEditing
              ? "bg-background text-foreground"
              : "bg-white text-foreground border-dashed border-muted-foreground/40 cursor-default"
          }
        `}
        placeholder='Example: "#20 DO filling"'
        value={notes}
        onChange={(e) => setNotes(e.target.value)}
        readOnly={!isEditing}
      />

      {/* View-mode hint */}
      {!isEditing && (
        <div className="text-xs text-muted-foreground">
          View only — click <span className="font-medium">Edit</span> to modify
        </div>
      )}
    </div>
  );
}
