'use client'

import { useCallback } from 'react'
import {
  Block,
  TextBlock,
  DividerBlock,
  CTABlock,
  ImageBlock,
  SpacerBlock,
  SocialBlock,
  HeaderBlock,
  FooterBlock,
  SocialLink,
  BlockStyle,
} from '../types'
import { Button } from '../../ui/button'
import { Input } from '../../ui/input'
import { Label } from '../../ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../ui/select'
import { Plus, Trash2 } from 'lucide-react'

interface BlockPropertyPanelProps {
  block: Block
  onChange: (block: Block) => void
}

export function BlockPropertyPanel({ block, onChange }: BlockPropertyPanelProps) {
  const updateStyle = useCallback(
    (updates: Partial<BlockStyle>) => {
      onChange({ ...block, style: { ...block.style, ...updates } })
    },
    [block, onChange]
  )

  return (
    <div className="space-y-4">
      <div className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
        {block.type} Settings
      </div>

      {/* Type-specific settings */}
      {block.type === 'text' && (
        <TextSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'divider' && (
        <DividerSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'cta' && (
        <ButtonSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'image' && (
        <ImageSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'spacer' && (
        <SpacerSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'social' && (
        <SocialSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'header' && (
        <HeaderSettings block={block} onChange={(b) => onChange(b)} />
      )}
      {block.type === 'footer' && (
        <FooterSettings block={block} onChange={(b) => onChange(b)} />
      )}

      {/* Common: spacing/background */}
      <div className="border-t pt-4 space-y-3">
        <div className="text-xs font-medium text-muted-foreground">Spacing</div>
        <div className="grid grid-cols-2 gap-2">
          <div className="space-y-1">
            <Label className="text-xs">Pad Top</Label>
            <Input
              type="number"
              value={block.style?.paddingTop ?? 0}
              onChange={(e) => updateStyle({ paddingTop: parseInt(e.target.value) || 0 })}
              className="h-8 text-xs"
            />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">Pad Bottom</Label>
            <Input
              type="number"
              value={block.style?.paddingBottom ?? 0}
              onChange={(e) => updateStyle({ paddingBottom: parseInt(e.target.value) || 0 })}
              className="h-8 text-xs"
            />
          </div>
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Background</Label>
          <div className="flex gap-2">
            <input
              type="color"
              value={block.style?.backgroundColor || '#ffffff'}
              onChange={(e) => updateStyle({ backgroundColor: e.target.value })}
              className="h-8 w-8 rounded border cursor-pointer"
            />
            <Input
              value={block.style?.backgroundColor || ''}
              onChange={(e) => updateStyle({ backgroundColor: e.target.value })}
              placeholder="transparent"
              className="h-8 text-xs"
            />
          </div>
        </div>
      </div>
    </div>
  )
}

// --- Text settings ---
function TextSettings({ block, onChange }: { block: TextBlock; onChange: (b: TextBlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Font Size (px)</Label>
        <Input
          type="number"
          value={block.fontSize || 16}
          onChange={(e) => onChange({ ...block, fontSize: parseInt(e.target.value) || 16 })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Line Height</Label>
        <Input
          type="number"
          step="0.1"
          value={block.lineHeight || 1.6}
          onChange={(e) => onChange({ ...block, lineHeight: parseFloat(e.target.value) || 1.6 })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Text Color</Label>
        <div className="flex gap-2">
          <input
            type="color"
            value={block.textColor || '#1f2937'}
            onChange={(e) => onChange({ ...block, textColor: e.target.value })}
            className="h-8 w-8 rounded border cursor-pointer"
          />
          <Input
            value={block.textColor || '#1f2937'}
            onChange={(e) => onChange({ ...block, textColor: e.target.value })}
            className="h-8 text-xs"
          />
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Font Family</Label>
        <Select
          value={block.fontFamily || 'default'}
          onValueChange={(v) => onChange({ ...block, fontFamily: v === 'default' ? undefined : v })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="default">Default</SelectItem>
            <SelectItem value="Arial, sans-serif">Arial</SelectItem>
            <SelectItem value="Georgia, serif">Georgia</SelectItem>
            <SelectItem value="'Courier New', monospace">Courier New</SelectItem>
            <SelectItem value="Verdana, sans-serif">Verdana</SelectItem>
            <SelectItem value="'Trebuchet MS', sans-serif">Trebuchet MS</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  )
}

// --- Divider settings ---
function DividerSettings({ block, onChange }: { block: DividerBlock; onChange: (b: DividerBlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Style</Label>
        <Select
          value={block.dividerStyle}
          onValueChange={(v) => onChange({ ...block, dividerStyle: v as DividerBlock['dividerStyle'] })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="solid">Solid</SelectItem>
            <SelectItem value="dashed">Dashed</SelectItem>
            <SelectItem value="dotted">Dotted</SelectItem>
            <SelectItem value="space">Space</SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Color</Label>
        <div className="flex gap-2">
          <input
            type="color"
            value={block.color || '#d1d5db'}
            onChange={(e) => onChange({ ...block, color: e.target.value })}
            className="h-8 w-8 rounded border cursor-pointer"
          />
          <Input
            value={block.color || '#d1d5db'}
            onChange={(e) => onChange({ ...block, color: e.target.value })}
            className="h-8 text-xs"
          />
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Thickness (px)</Label>
        <Input
          type="number"
          value={block.thickness || 1}
          onChange={(e) => onChange({ ...block, thickness: parseInt(e.target.value) || 1 })}
          className="h-8 text-xs"
          min={1}
          max={10}
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Width (%)</Label>
        <Input
          type="number"
          value={block.width || 100}
          onChange={(e) => onChange({ ...block, width: parseInt(e.target.value) || 100 })}
          className="h-8 text-xs"
          min={10}
          max={100}
        />
      </div>
    </div>
  )
}

// --- Button settings ---
function ButtonSettings({ block, onChange }: { block: CTABlock; onChange: (b: CTABlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Button Text</Label>
        <Input
          value={block.text}
          onChange={(e) => onChange({ ...block, text: e.target.value })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">URL</Label>
        <Input
          value={block.url}
          onChange={(e) => onChange({ ...block, url: e.target.value })}
          placeholder="https://..."
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Button Color</Label>
        <div className="flex gap-2">
          <input
            type="color"
            value={block.buttonColor || '#2563eb'}
            onChange={(e) => onChange({ ...block, buttonColor: e.target.value })}
            className="h-8 w-8 rounded border cursor-pointer"
          />
          <Input
            value={block.buttonColor || '#2563eb'}
            onChange={(e) => onChange({ ...block, buttonColor: e.target.value })}
            className="h-8 text-xs"
          />
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Text Color</Label>
        <div className="flex gap-2">
          <input
            type="color"
            value={block.textColor || '#ffffff'}
            onChange={(e) => onChange({ ...block, textColor: e.target.value })}
            className="h-8 w-8 rounded border cursor-pointer"
          />
          <Input
            value={block.textColor || '#ffffff'}
            onChange={(e) => onChange({ ...block, textColor: e.target.value })}
            className="h-8 text-xs"
          />
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Border Radius (px)</Label>
        <Input
          type="number"
          value={block.borderRadius ?? 6}
          onChange={(e) => onChange({ ...block, borderRadius: parseInt(e.target.value) || 0 })}
          className="h-8 text-xs"
          min={0}
          max={50}
        />
      </div>
      <div className="grid grid-cols-2 gap-2">
        <div className="space-y-1">
          <Label className="text-xs">Pad H</Label>
          <Input
            type="number"
            value={block.paddingH ?? 24}
            onChange={(e) => onChange({ ...block, paddingH: parseInt(e.target.value) || 0 })}
            className="h-8 text-xs"
          />
        </div>
        <div className="space-y-1">
          <Label className="text-xs">Pad V</Label>
          <Input
            type="number"
            value={block.paddingV ?? 12}
            onChange={(e) => onChange({ ...block, paddingV: parseInt(e.target.value) || 0 })}
            className="h-8 text-xs"
          />
        </div>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Alignment</Label>
        <Select
          value={block.alignment}
          onValueChange={(v) => onChange({ ...block, alignment: v as 'left' | 'center' | 'right' })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="left">Left</SelectItem>
            <SelectItem value="center">Center</SelectItem>
            <SelectItem value="right">Right</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  )
}

// --- Image settings ---
function ImageSettings({ block, onChange }: { block: ImageBlock; onChange: (b: ImageBlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Image URL</Label>
        <Input
          value={block.url}
          onChange={(e) => onChange({ ...block, url: e.target.value })}
          placeholder="https://..."
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Alt Text</Label>
        <Input
          value={block.alt}
          onChange={(e) => onChange({ ...block, alt: e.target.value })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Caption</Label>
        <Input
          value={block.caption || ''}
          onChange={(e) => onChange({ ...block, caption: e.target.value })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Link URL (wraps image)</Label>
        <Input
          value={block.linkUrl || ''}
          onChange={(e) => onChange({ ...block, linkUrl: e.target.value })}
          placeholder="https://..."
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Width (%)</Label>
        <Input
          type="number"
          value={block.width || 100}
          onChange={(e) => onChange({ ...block, width: parseInt(e.target.value) || 100 })}
          className="h-8 text-xs"
          min={10}
          max={100}
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Alignment</Label>
        <Select
          value={block.alignment}
          onValueChange={(v) => onChange({ ...block, alignment: v as 'left' | 'center' | 'right' })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="left">Left</SelectItem>
            <SelectItem value="center">Center</SelectItem>
            <SelectItem value="right">Right</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  )
}

// --- Spacer settings ---
function SpacerSettings({ block, onChange }: { block: SpacerBlock; onChange: (b: SpacerBlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Height (px)</Label>
        <Input
          type="number"
          value={block.height || 32}
          onChange={(e) => onChange({ ...block, height: parseInt(e.target.value) || 8 })}
          className="h-8 text-xs"
          min={8}
          max={200}
        />
      </div>
    </div>
  )
}

// --- Social settings ---
function SocialSettings({ block, onChange }: { block: SocialBlock; onChange: (b: SocialBlock) => void }) {
  const addLink = () => {
    const link: SocialLink = {
      id: `social-${Date.now()}`,
      platform: 'website',
      url: '',
    }
    onChange({ ...block, links: [...block.links, link] })
  }

  const removeLink = (id: string) => {
    onChange({ ...block, links: block.links.filter((l) => l.id !== id) })
  }

  const updateLink = (id: string, updates: Partial<SocialLink>) => {
    onChange({
      ...block,
      links: block.links.map((l) => (l.id === id ? { ...l, ...updates } : l)),
    })
  }

  const platforms: SocialLink['platform'][] = [
    'linkedin', 'twitter', 'facebook', 'instagram', 'youtube', 'github', 'website',
  ]

  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Alignment</Label>
        <Select
          value={block.alignment}
          onValueChange={(v) => onChange({ ...block, alignment: v as 'left' | 'center' | 'right' })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="left">Left</SelectItem>
            <SelectItem value="center">Center</SelectItem>
            <SelectItem value="right">Right</SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Icon Size</Label>
        <Input
          type="number"
          value={block.iconSize || 24}
          onChange={(e) => onChange({ ...block, iconSize: parseInt(e.target.value) || 24 })}
          className="h-8 text-xs"
          min={16}
          max={48}
        />
      </div>
      <div className="space-y-2">
        <Label className="text-xs">Links</Label>
        {block.links.map((link) => (
          <div key={link.id} className="flex gap-1 items-center">
            <Select
              value={link.platform}
              onValueChange={(v) =>
                updateLink(link.id, { platform: v as SocialLink['platform'] })
              }
            >
              <SelectTrigger className="h-7 text-xs w-24 shrink-0">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {platforms.map((p) => (
                  <SelectItem key={p} value={p} className="text-xs">
                    {p.charAt(0).toUpperCase() + p.slice(1)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Input
              value={link.url}
              onChange={(e) => updateLink(link.id, { url: e.target.value })}
              placeholder="URL"
              className="h-7 text-xs"
            />
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7 shrink-0"
              onClick={() => removeLink(link.id)}
            >
              <Trash2 className="h-3 w-3" />
            </Button>
          </div>
        ))}
        <Button variant="outline" size="sm" onClick={addLink} className="w-full h-7 text-xs">
          <Plus className="mr-1 h-3 w-3" />
          Add Link
        </Button>
      </div>
    </div>
  )
}

// --- Header settings ---
function HeaderSettings({ block, onChange }: { block: HeaderBlock; onChange: (b: HeaderBlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Company Name</Label>
        <Input
          value={block.companyName}
          onChange={(e) => onChange({ ...block, companyName: e.target.value })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Logo URL</Label>
        <Input
          value={block.logoUrl || ''}
          onChange={(e) => onChange({ ...block, logoUrl: e.target.value })}
          placeholder="https://..."
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Alignment</Label>
        <Select
          value={block.alignment}
          onValueChange={(v) => onChange({ ...block, alignment: v as 'left' | 'center' | 'right' })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="left">Left</SelectItem>
            <SelectItem value="center">Center</SelectItem>
            <SelectItem value="right">Right</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  )
}

// --- Footer settings ---
function FooterSettings({ block, onChange }: { block: FooterBlock; onChange: (b: FooterBlock) => void }) {
  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="text-xs">Company Name</Label>
        <Input
          value={block.companyName}
          onChange={(e) => onChange({ ...block, companyName: e.target.value })}
          className="h-8 text-xs"
        />
      </div>
      <div className="space-y-1">
        <Label className="text-xs">Address</Label>
        <Input
          value={block.address || ''}
          onChange={(e) => onChange({ ...block, address: e.target.value })}
          className="h-8 text-xs"
        />
      </div>
      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          checked={block.showUnsubscribe}
          onChange={(e) => onChange({ ...block, showUnsubscribe: e.target.checked })}
          className="rounded"
          id="show-unsub"
        />
        <Label className="text-xs" htmlFor="show-unsub">Show unsubscribe link</Label>
      </div>
      {block.showUnsubscribe && (
        <div className="space-y-1">
          <Label className="text-xs">Unsubscribe URL</Label>
          <Input
            value={block.unsubscribeUrl || ''}
            onChange={(e) => onChange({ ...block, unsubscribeUrl: e.target.value })}
            placeholder="https://..."
            className="h-8 text-xs"
          />
        </div>
      )}
      <div className="space-y-1">
        <Label className="text-xs">Alignment</Label>
        <Select
          value={block.alignment}
          onValueChange={(v) => onChange({ ...block, alignment: v as 'left' | 'center' | 'right' })}
        >
          <SelectTrigger className="h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="left">Left</SelectItem>
            <SelectItem value="center">Center</SelectItem>
            <SelectItem value="right">Right</SelectItem>
          </SelectContent>
        </Select>
      </div>
    </div>
  )
}
