/**
 * Branding Section
 * Logo upload and alignment settings
 */

import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { ChevronDown, Image, Trash2, AlertCircle } from 'lucide-react';
import { useState } from 'react';
import type { EmailLogo } from '../types';

interface WPMediaAttachment {
  url: string;
  id: number;
}

interface WPMediaSelection {
  first: () => {
    toJSON: () => WPMediaAttachment;
  };
}

interface WPMediaState {
  get: (key: string) => WPMediaSelection;
}

interface WPMediaFrame {
  on: (event: string, callback: () => void) => WPMediaFrame;
  open: () => void;
  state: () => WPMediaState;
}

interface WPMedia {
  (options: {
    title: string;
    button: { text: string };
    multiple: boolean;
    library?: { type: string };
  }): WPMediaFrame;
  frames?: Record<string, WPMediaFrame>;
}

declare global {
  interface Window {
    wp?: {
      media?: WPMedia;
    };
  }
}

interface BrandingSectionProps {
  logo: EmailLogo;
  onUpdate: (updates: Partial<EmailLogo>) => void;
}

export function BrandingSection({ logo, onUpdate }: BrandingSectionProps) {
  const [isOpen, setIsOpen] = useState(true);
  const [mediaError, setMediaError] = useState<string | null>(null);

  const handleSelectLogo = () => {
    setMediaError(null);
    
    // Check if WordPress media library is available
    if (!window.wp?.media) {
      setMediaError('WordPress media library is not available. Please refresh the page.');
      console.error('WordPress media library not available. window.wp:', window.wp);
      return;
    }

    // Always create a new frame to avoid stale state issues
    const frame = window.wp.media({
      title: 'Select Logo',
      button: { text: 'Select' },
      multiple: false,
    });

    frame.on('select', () => {
      const attachment = frame.state().get('selection').first().toJSON();
      if (attachment?.url) {
        onUpdate({ url: attachment.url });
      }
    });

    frame.open();
  };

  const handleRemoveLogo = () => {
    onUpdate({ url: '' });
  };

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <CollapsibleTrigger className="flex items-center justify-between w-full p-4 border-b hover:bg-muted/50 transition-colors">
        <div className="flex items-center gap-2">
          <Image className="h-4 w-4 text-muted-foreground" />
          <span className="font-medium">Branding</span>
        </div>
        <ChevronDown
          className={`h-4 w-4 text-muted-foreground transition-transform ${
            isOpen ? 'rotate-180' : ''
          }`}
        />
      </CollapsibleTrigger>
      <CollapsibleContent className="p-4 space-y-4 border-b">
        {/* Media Error Message */}
        {mediaError && (
          <div className="flex items-center gap-2 p-3 bg-destructive/10 text-destructive rounded-md text-sm">
            <AlertCircle className="h-4 w-4 flex-shrink-0" />
            {mediaError}
          </div>
        )}
        
        {/* Logo Upload */}
        <div className="space-y-2">
          <Label>Logo</Label>
          {logo.url ? (
            <div className="space-y-2">
              <div className="relative border rounded-md p-2 bg-muted/30">
                <img
                  src={logo.url}
                  alt="Email logo"
                  className="max-h-16 object-contain mx-auto"
                />
                <Button
                  variant="destructive"
                  size="icon"
                  className="absolute top-1 right-1 h-6 w-6"
                  onClick={handleRemoveLogo}
                >
                  <Trash2 className="h-3 w-3" />
                </Button>
              </div>
              <Button
                variant="outline"
                size="sm"
                className="w-full"
                onClick={handleSelectLogo}
              >
                Change Logo
              </Button>
            </div>
          ) : (
            <Button
              variant="outline"
              className="w-full"
              onClick={handleSelectLogo}
            >
              <Image className="h-4 w-4 mr-2" />
              Upload Logo
            </Button>
          )}
        </div>

        {/* Logo Width */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <Label>Logo Width</Label>
            <span className="text-sm text-muted-foreground">{logo.width}px</span>
          </div>
          <Slider
            value={[logo.width]}
            onValueChange={([value]) => onUpdate({ width: value })}
            min={50}
            max={400}
            step={10}
          />
        </div>

        {/* Logo Alignment */}
        <div className="space-y-2">
          <Label>Logo Alignment</Label>
          <Select
            value={logo.alignment}
            onValueChange={(value: 'left' | 'center' | 'right') =>
              onUpdate({ alignment: value })
            }
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="left">Left</SelectItem>
              <SelectItem value="center">Center</SelectItem>
              <SelectItem value="right">Right</SelectItem>
            </SelectContent>
          </Select>
        </div>

      </CollapsibleContent>
    </Collapsible>
  );
}

export default BrandingSection;
