import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
import { usePageHeader } from '@/contexts/PageHeaderContext';

import { DocLink } from '@/components/DocLink';

interface SettingsLayoutProps {
  title: string | React.ReactNode;
  description?: string;
  children: React.ReactNode;
  onSave?: () => Promise<void>;
  saveLabel?: string;
  isLoading?: boolean;
  action?: React.ReactNode;
}

export function SettingsLayout({
  title,
  description,
  children,
  onSave,
  saveLabel = 'Save changes',
  isLoading = false,
  action,
}: SettingsLayoutProps) {
  const [isSaving, setIsSaving] = useState(false);
  const { setPageHeader, clearPageHeader } = usePageHeader();

  const handleSave = async () => {
    if (!onSave) return;
    setIsSaving(true);
    try {
      await onSave();
    } finally {
      setIsSaving(false);
    }
  };

  // Set page header ONLY when there's an action (Save button or custom action)
  // This saves vertical space on pages without actions
  useEffect(() => {
    // Extract string title if it's a ReactNode
    const titleString = typeof title === 'string' ? title : '';

    if (onSave) {
      // Combine custom action with save button
      const headerAction = (
        <div className="flex items-center gap-2">
          {action}
          <Button
            onClick={handleSave}
            disabled={isSaving || isLoading}
            size="sm"
          >
            {isSaving ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Saving...
              </>
            ) : (
              saveLabel
            )}
          </Button>
        </div>
      );
      setPageHeader(titleString, headerAction);
    } else if (action) {
      // If there's a custom action, use it
      setPageHeader(titleString, action);
    } else {
      // No action = no header (save vertical space)
      clearPageHeader();
    }

    return () => clearPageHeader();
  }, [title, onSave, isSaving, isLoading, saveLabel, action, setPageHeader, clearPageHeader]);

  return (
    <div className="space-y-6 min-w-0">

      {/* Content */}
      <div className="w-full max-w-5xl mx-auto min-w-0">
        {/* Only show inline header if NOT using contextual header (no onSave and no action) */}
        {!onSave && !action && (
          <div className="mb-8">
            <div className="flex items-start justify-between gap-4 min-w-0">
              <div className="min-w-0 flex-1">
                <div className="flex items-center">
                  <h1 className="text-2xl font-bold tracking-tight">{title}</h1>
                  <DocLink />
                </div>
                {description && (
                  <p className="text-muted-foreground mt-2">{description}</p>
                )}
              </div>
            </div>
          </div>
        )}

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <div className="space-y-6 min-w-0">{children}</div>
        )}
      </div>
    </div>
  );
}
