import { useState, useEffect, useMemo, forwardRef, useImperativeHandle } from 'react'
import {
  Plus,
  X,
  Search,
  ChevronDown,
  ChevronRight,
  AlertCircle,
  Loader2,
  ClipboardPaste,
} from 'lucide-react'
import { api } from '../lib/api'
import { notificationManager } from '../lib/notificationManager'

interface Account {
  username: string
  posts: boolean
  stories: boolean
  reels: boolean
  tagged: boolean
}

interface ContentTypeConfig {
  enabled: boolean
  days_back: number
  destination_path: string
}

interface PhraseSearch {
  enabled: boolean
  download_all: boolean
  phrases: string[]
  case_sensitive: boolean
  match_all: boolean
}

interface UnifiedConfig {
  enabled: boolean
  check_interval_hours: number
  run_at_start: boolean
  user_delay_seconds: number
  scraper_assignment: Record<string, string>
  content_types: Record<string, ContentTypeConfig>
  accounts: Account[]
  phrase_search: PhraseSearch
  scraper_settings: Record<string, Record<string, any>>
}

const CONTENT_TYPES = ['posts', 'stories', 'reels', 'tagged'] as const
type ContentType = typeof CONTENT_TYPES[number]

const CONTENT_TYPE_LABELS: Record<string, string> = {
  posts: 'Posts',
  stories: 'Stories',
  reels: 'Reels',
  tagged: 'Tagged',
}

export interface InstagramUnifiedRef {
  save: () => Promise<void>
  isSaving: boolean
}

const InstagramUnified = forwardRef<InstagramUnifiedRef>(function InstagramUnified(_props, ref) {
  const [config, setConfig] = useState<UnifiedConfig | null>(null)
  const [hiddenModules, setHiddenModules] = useState<string[]>([])
  const [scraperCapabilities, setScraperCapabilities] = useState<Record<string, Record<string, boolean>>>({})
  const [scraperLabels, setScraperLabels] = useState<Record<string, string>>({})
  const [isMigrated, setIsMigrated] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [showPasteModal, setShowPasteModal] = useState(false)
  const [pasteText, setPasteText] = useState('')
  const [phraseSearchOpen, setPhraseSearchOpen] = useState(false)
  const [scraperSettingsOpen, setScraperSettingsOpen] = useState(false)
  const [newUsername, setNewUsername] = useState('')

  useImperativeHandle(ref, () => ({
    save: saveConfig,
    isSaving,
  }), [config, isSaving])

  useEffect(() => {
    loadConfig()
  }, [])

  const loadConfig = async () => {
    try {
      setIsLoading(true)
      const data = await api.getInstagramUnifiedConfig()
      setConfig(data.config as unknown as UnifiedConfig)
      setHiddenModules(data.hidden_modules)
      setScraperCapabilities(data.scraper_capabilities)
      setScraperLabels(data.scraper_labels)
      setIsMigrated(data.migrated)
    } catch (err) {
      console.error('Failed to load config:', err)
    } finally {
      setIsLoading(false)
    }
  }

  const saveConfig = async () => {
    if (!config) return
    setIsSaving(true)
    try {
      await api.updateInstagramUnifiedConfig(config as unknown as Record<string, any>)
      notificationManager.settingsSaved('Instagram')
      setIsMigrated(false)
    } catch (err: any) {
      notificationManager.settingsSaveError(err, 'Instagram')
    } finally {
      setIsSaving(false)
    }
  }

  const updateConfig = (updates: Partial<UnifiedConfig>) => {
    if (!config) return
    setConfig({ ...config, ...updates })
  }

  const updateContentType = (ct: string, updates: Partial<ContentTypeConfig>) => {
    if (!config) return
    setConfig({
      ...config,
      content_types: {
        ...config.content_types,
        [ct]: { ...config.content_types[ct], ...updates }
      }
    })
  }

  const updateScraperAssignment = (ct: string, scraper: string) => {
    if (!config) return
    setConfig({
      ...config,
      scraper_assignment: { ...config.scraper_assignment, [ct]: scraper }
    })
  }

  const updateAccount = (index: number, updates: Partial<Account>) => {
    if (!config) return
    const newAccounts = [...config.accounts]
    newAccounts[index] = { ...newAccounts[index], ...updates }
    setConfig({ ...config, accounts: newAccounts })
  }

  const removeAccount = (index: number) => {
    if (!config) return
    const newAccounts = config.accounts.filter((_, i) => i !== index)
    setConfig({ ...config, accounts: newAccounts })
  }

  const addAccount = (username: string) => {
    if (!config || !username.trim()) return
    const trimmed = username.trim().toLowerCase().replace(/^@/, '')
    if (config.accounts.some(a => a.username === trimmed)) return
    setConfig({
      ...config,
      accounts: [...config.accounts, { username: trimmed, posts: true, stories: true, reels: true, tagged: false }]
    })
  }

  const handleAddUsername = () => {
    if (newUsername.trim()) {
      addAccount(newUsername)
      setNewUsername('')
    }
  }

  const handlePaste = () => {
    const usernames = pasteText
      .split(/[\n,;]+/)
      .map(u => u.trim().toLowerCase().replace(/^@/, ''))
      .filter(u => u && !config?.accounts.some(a => a.username === u))

    if (config && usernames.length > 0) {
      const newAccounts = usernames.map(username => ({
        username,
        posts: true,
        stories: true,
        reels: true,
        tagged: false,
      }))
      setConfig({ ...config, accounts: [...config.accounts, ...newAccounts] })
    }
    setPasteText('')
    setShowPasteModal(false)
  }

  const updatePhraseSearch = (updates: Partial<PhraseSearch>) => {
    if (!config) return
    setConfig({
      ...config,
      phrase_search: { ...config.phrase_search, ...updates }
    })
  }

  const updateScraperSettings = (scraper: string, updates: Record<string, any>) => {
    if (!config) return
    setConfig({
      ...config,
      scraper_settings: {
        ...config.scraper_settings,
        [scraper]: { ...config.scraper_settings[scraper], ...updates }
      }
    })
  }

  // Get available scrapers for a content type (supports it + not hidden)
  const getAvailableScrapers = (ct: string): string[] => {
    return Object.entries(scraperCapabilities)
      .filter(([key, caps]) => caps[ct] && !hiddenModules.includes(key))
      .map(([key]) => key)
  }

  // Filtered accounts based on search
  const filteredAccounts = useMemo(() => {
    if (!config) return []
    if (!searchQuery) return config.accounts
    const q = searchQuery.toLowerCase()
    return config.accounts.filter(a => a.username.toLowerCase().includes(q))
  }, [config?.accounts, searchQuery])

  // Filtered indices for select-all operations
  const filteredIndices = useMemo(() => {
    if (!config) return []
    if (!searchQuery) return config.accounts.map((_, i) => i)
    const q = searchQuery.toLowerCase()
    return config.accounts.reduce<number[]>((acc, a, i) => {
      if (a.username.toLowerCase().includes(q)) acc.push(i)
      return acc
    }, [])
  }, [config?.accounts, searchQuery])

  // Column select-all state
  const getColumnState = (ct: ContentType): 'all' | 'none' | 'some' => {
    if (filteredAccounts.length === 0) return 'none'
    const checked = filteredAccounts.filter(a => a[ct]).length
    if (checked === filteredAccounts.length) return 'all'
    if (checked === 0) return 'none'
    return 'some'
  }

  const toggleColumn = (ct: ContentType) => {
    if (!config) return
    const state = getColumnState(ct)
    const newValue = state !== 'all'
    const newAccounts = [...config.accounts]
    filteredIndices.forEach(i => {
      newAccounts[i] = { ...newAccounts[i], [ct]: newValue }
    })
    setConfig({ ...config, accounts: newAccounts })
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-6 h-6 animate-spin text-purple-500 mr-3" />
        <span className="text-slate-600 dark:text-slate-400">Loading Instagram configuration...</span>
      </div>
    )
  }

  if (!config) {
    return (
      <div className="text-center py-12 text-slate-500 dark:text-slate-400">
        Failed to load configuration
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="card-glass rounded-xl overflow-hidden">
        <div className="bg-gradient-to-r from-purple-50 to-pink-50 dark:from-purple-900/20 dark:to-pink-900/20 border-b border-slate-200 dark:border-slate-700 px-5 py-4 flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-gradient-to-br from-purple-600 to-pink-600 rounded-lg flex items-center justify-center">
              <span className="text-white font-bold text-sm">IG</span>
            </div>
            <div>
              <h3 className="font-semibold text-slate-900 dark:text-slate-100">Instagram Configuration</h3>
              <p className="text-xs text-slate-500 dark:text-slate-400">Unified scraper management</p>
            </div>
          </div>
          <label className="flex items-center space-x-2 cursor-pointer">
            <input
              type="checkbox"
              checked={config.enabled}
              onChange={e => updateConfig({ enabled: e.target.checked })}
              className="w-4 h-4 rounded border-slate-300"
            />
            <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Enabled</span>
          </label>
        </div>

        {/* Migration banner */}
        {isMigrated && (
          <div className="px-5 py-3 bg-amber-50 dark:bg-amber-900/20 border-b border-amber-200 dark:border-amber-800">
            <div className="flex items-center space-x-2 text-sm text-amber-700 dark:text-amber-300">
              <AlertCircle className="w-4 h-4" />
              <span>Configuration migrated from legacy scrapers. Review and save to apply.</span>
            </div>
          </div>
        )}

        {/* Global settings */}
        <div className="p-5 space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Check Interval (hours)</label>
              <input
                type="number"
                min="1"
                value={config.check_interval_hours}
                onChange={e => updateConfig({ check_interval_hours: parseInt(e.target.value) || 8 })}
                className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-purple-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">User Delay (seconds)</label>
              <input
                type="number"
                min="0"
                value={config.user_delay_seconds}
                onChange={e => updateConfig({ user_delay_seconds: parseInt(e.target.value) || 20 })}
                className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-purple-500"
              />
            </div>
            <div className="flex items-end">
              <label className="flex items-center space-x-2 cursor-pointer pb-2">
                <input
                  type="checkbox"
                  checked={config.run_at_start}
                  onChange={e => updateConfig({ run_at_start: e.target.checked })}
                  className="w-4 h-4 rounded border-slate-300"
                />
                <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Run at Start</span>
              </label>
            </div>
          </div>
        </div>
      </div>

      {/* Scraper Assignment */}
      <div className="card-glass rounded-xl overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-200 dark:border-slate-700">
          <h4 className="font-medium text-slate-900 dark:text-slate-100 text-sm uppercase tracking-wide">Scraper Assignment</h4>
          <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Choose which scraper handles each content type</p>
        </div>
        <div className="p-5">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {CONTENT_TYPES.map(ct => {
              const available = getAvailableScrapers(ct)
              const currentScraper = config.scraper_assignment[ct]
              return (
                <div key={ct}>
                  <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                    {CONTENT_TYPE_LABELS[ct]}
                  </label>
                  <select
                    value={currentScraper || ''}
                    onChange={e => updateScraperAssignment(ct, e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-purple-500 text-sm"
                  >
                    {available.map(s => (
                      <option key={s} value={s}>{scraperLabels[s] || s}</option>
                    ))}
                    {/* Show current even if hidden */}
                    {currentScraper && !available.includes(currentScraper) && (
                      <option value={currentScraper}>{scraperLabels[currentScraper] || currentScraper} (hidden)</option>
                    )}
                  </select>
                </div>
              )
            })}
          </div>
        </div>
      </div>

      {/* Content Settings */}
      <div className="card-glass rounded-xl overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-200 dark:border-slate-700">
          <h4 className="font-medium text-slate-900 dark:text-slate-100 text-sm uppercase tracking-wide">Content Settings</h4>
        </div>
        <div className="p-5 space-y-3">
          {CONTENT_TYPES.map(ct => {
            const ctConfig = config.content_types[ct] || { enabled: false, days_back: 7, destination_path: '' }
            return (
              <div key={ct} className="flex flex-wrap items-center gap-3 p-3 rounded-lg bg-slate-50 dark:bg-slate-800/50">
                <label className="flex items-center space-x-2 cursor-pointer min-w-[100px]">
                  <input
                    type="checkbox"
                    checked={ctConfig.enabled}
                    onChange={e => updateContentType(ct, { enabled: e.target.checked })}
                    className="w-4 h-4 rounded border-slate-300"
                  />
                  <span className="text-sm font-medium text-slate-700 dark:text-slate-300">{CONTENT_TYPE_LABELS[ct]}</span>
                </label>
                <div className="flex items-center space-x-2">
                  <label className="text-xs text-slate-500 dark:text-slate-400">Days:</label>
                  <input
                    type="number"
                    min="1"
                    value={ctConfig.days_back}
                    onChange={e => updateContentType(ct, { days_back: parseInt(e.target.value) || 7 })}
                    className="w-16 px-2 py-1 border border-slate-300 dark:border-slate-600 rounded bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
                <div className="flex-1 min-w-[200px]">
                  <input
                    type="text"
                    value={ctConfig.destination_path}
                    onChange={e => updateContentType(ct, { destination_path: e.target.value })}
                    className="w-full px-2 py-1 border border-slate-300 dark:border-slate-600 rounded bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-xs focus:ring-2 focus:ring-purple-500"
                    placeholder={`/opt/immich/md/social media/instagram/${ct}`}
                  />
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* Accounts */}
      <div className="card-glass rounded-xl overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-200 dark:border-slate-700 flex flex-wrap items-center justify-between gap-2">
          <div>
            <h4 className="font-medium text-slate-900 dark:text-slate-100 text-sm uppercase tracking-wide">
              Accounts ({config.accounts.length})
            </h4>
          </div>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="w-4 h-4 absolute left-2 top-1/2 -translate-y-1/2 text-slate-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                placeholder="Search..."
                className="w-40 pl-8 pr-3 py-1.5 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
              />
            </div>
            <div className="flex items-center space-x-1">
              <input
                type="text"
                value={newUsername}
                onChange={e => setNewUsername(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') handleAddUsername() }}
                placeholder="Add username"
                className="w-32 px-2 py-1.5 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
              />
              <button
                onClick={handleAddUsername}
                className="p-1.5 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
                title="Add account"
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
            <button
              onClick={() => setShowPasteModal(true)}
              className="flex items-center space-x-1 px-2 py-1.5 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-300 rounded-lg text-sm transition-colors"
              title="Paste list of usernames"
            >
              <ClipboardPaste className="w-4 h-4" />
              <span className="hidden sm:inline">Paste</span>
            </button>
          </div>
        </div>

        {/* Column select-all */}
        <div className="px-5 py-2 border-b border-slate-200 dark:border-slate-700 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50">
          <span className="text-xs text-slate-500 dark:text-slate-400 mr-2">Toggle all:</span>
          {CONTENT_TYPES.map(ct => {
            const state = getColumnState(ct)
            return (
              <button
                key={ct}
                onClick={() => toggleColumn(ct)}
                className={`px-2 py-1 rounded text-xs font-medium transition-colors ${
                  state === 'all'
                    ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300'
                    : state === 'some'
                    ? 'bg-purple-50 dark:bg-purple-900/15 text-purple-500 dark:text-purple-400'
                    : 'bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400'
                }`}
              >
                {state === 'all' ? '\u2611' : state === 'some' ? '\u25A3' : '\u2610'} {CONTENT_TYPE_LABELS[ct]}
              </button>
            )
          })}
        </div>

        {/* Account list */}
        <div className="max-h-[500px] overflow-y-auto">
          <table className="w-full text-sm">
            <thead className="sticky top-0 bg-slate-50 dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700">
              <tr>
                <th className="text-left px-5 py-2 text-xs font-medium text-slate-500 dark:text-slate-400 uppercase">Username</th>
                {CONTENT_TYPES.map(ct => (
                  <th key={ct} className="text-center px-2 py-2 text-xs font-medium text-slate-500 dark:text-slate-400 uppercase w-16">{CONTENT_TYPE_LABELS[ct]}</th>
                ))}
                <th className="text-center px-2 py-2 w-10"></th>
              </tr>
            </thead>
            <tbody>
              {filteredAccounts.map((account) => {
                const realIndex = config.accounts.indexOf(account)
                return (
                  <tr key={account.username} className="border-b border-slate-100 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-800/30">
                    <td className="px-5 py-1.5 font-mono text-slate-900 dark:text-slate-100">{account.username}</td>
                    {CONTENT_TYPES.map(ct => (
                      <td key={ct} className="text-center px-2 py-1.5">
                        <input
                          type="checkbox"
                          checked={account[ct]}
                          onChange={e => updateAccount(realIndex, { [ct]: e.target.checked })}
                          className="w-4 h-4 rounded border-slate-300 text-purple-600 focus:ring-purple-500"
                        />
                      </td>
                    ))}
                    <td className="text-center px-2 py-1.5">
                      <button
                        onClick={() => removeAccount(realIndex)}
                        className="p-0.5 text-slate-400 hover:text-red-500 transition-colors"
                        title="Remove account"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
          {filteredAccounts.length === 0 && searchQuery && (
            <div className="text-center py-6 text-slate-500 dark:text-slate-400 text-sm">
              No accounts matching "{searchQuery}"
            </div>
          )}
        </div>
      </div>

      {/* Phrase Search (collapsible) */}
      <div className="card-glass rounded-xl overflow-hidden">
        <button
          onClick={() => setPhraseSearchOpen(!phraseSearchOpen)}
          className="w-full px-5 py-3 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors"
        >
          <div className="flex items-center space-x-2">
            {phraseSearchOpen ? <ChevronDown className="w-4 h-4 text-slate-400" /> : <ChevronRight className="w-4 h-4 text-slate-400" />}
            <h4 className="font-medium text-slate-900 dark:text-slate-100 text-sm">Phrase Search</h4>
            {config.phrase_search.enabled && (
              <span className="px-2 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 text-xs rounded-full">Active</span>
            )}
          </div>
        </button>
        {phraseSearchOpen && (
          <div className="p-5 border-t border-slate-200 dark:border-slate-700 space-y-4">
            <div className="flex items-center space-x-4">
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.phrase_search.enabled}
                  onChange={e => updatePhraseSearch({ enabled: e.target.checked })}
                  className="w-4 h-4 rounded border-slate-300"
                />
                <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Enabled</span>
              </label>
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.phrase_search.download_all}
                  onChange={e => updatePhraseSearch({ download_all: e.target.checked })}
                  className="w-4 h-4 rounded border-slate-300"
                />
                <span className="text-sm text-slate-700 dark:text-slate-300">Download All Matches</span>
              </label>
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.phrase_search.case_sensitive}
                  onChange={e => updatePhraseSearch({ case_sensitive: e.target.checked })}
                  className="w-4 h-4 rounded border-slate-300"
                />
                <span className="text-sm text-slate-700 dark:text-slate-300">Case Sensitive</span>
              </label>
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.phrase_search.match_all}
                  onChange={e => updatePhraseSearch({ match_all: e.target.checked })}
                  className="w-4 h-4 rounded border-slate-300"
                />
                <span className="text-sm text-slate-700 dark:text-slate-300">Match All</span>
              </label>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Search Phrases (one per line)</label>
              <textarea
                value={config.phrase_search.phrases.join('\n')}
                onChange={e => updatePhraseSearch({ phrases: e.target.value.split('\n').filter(p => p.trim()) })}
                rows={4}
                className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-sm focus:ring-2 focus:ring-purple-500"
                placeholder="@evalongoria&#10;eva longoria"
              />
            </div>
          </div>
        )}
      </div>

      {/* Scraper Settings (collapsible) */}
      <div className="card-glass rounded-xl overflow-hidden">
        <button
          onClick={() => setScraperSettingsOpen(!scraperSettingsOpen)}
          className="w-full px-5 py-3 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors"
        >
          <div className="flex items-center space-x-2">
            {scraperSettingsOpen ? <ChevronDown className="w-4 h-4 text-slate-400" /> : <ChevronRight className="w-4 h-4 text-slate-400" />}
            <h4 className="font-medium text-slate-900 dark:text-slate-100 text-sm">Scraper Settings</h4>
            <span className="text-xs text-slate-500 dark:text-slate-400">(auth/credentials per scraper)</span>
          </div>
        </button>
        {scraperSettingsOpen && (
          <div className="p-5 border-t border-slate-200 dark:border-slate-700 space-y-6">
            {/* ImgInn */}
            <div>
              <h5 className="text-sm font-medium text-slate-900 dark:text-slate-100 mb-2">ImgInn</h5>
              <div>
                <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Cookie File</label>
                <input
                  type="text"
                  value={config.scraper_settings.imginn?.cookie_file || ''}
                  onChange={e => updateScraperSettings('imginn', { cookie_file: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-sm focus:ring-2 focus:ring-purple-500"
                  placeholder="cookies/imginn_cookies.json"
                />
              </div>
            </div>

            {/* Toolzu */}
            <div>
              <h5 className="text-sm font-medium text-slate-900 dark:text-slate-100 mb-2">Toolzu</h5>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Email</label>
                  <input
                    type="text"
                    value={config.scraper_settings.toolzu?.email || ''}
                    onChange={e => updateScraperSettings('toolzu', { email: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Password</label>
                  <input
                    type="password"
                    value={config.scraper_settings.toolzu?.password || ''}
                    onChange={e => updateScraperSettings('toolzu', { password: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Cookie File</label>
                  <input
                    type="text"
                    value={config.scraper_settings.toolzu?.cookie_file || ''}
                    onChange={e => updateScraperSettings('toolzu', { cookie_file: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
              </div>
            </div>

            {/* InstaLoader */}
            <div>
              <h5 className="text-sm font-medium text-slate-900 dark:text-slate-100 mb-2">InstaLoader</h5>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Login Username</label>
                  <input
                    type="text"
                    value={config.scraper_settings.instagram?.username || ''}
                    onChange={e => updateScraperSettings('instagram', { username: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Password</label>
                  <input
                    type="password"
                    value={config.scraper_settings.instagram?.password || ''}
                    onChange={e => updateScraperSettings('instagram', { password: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">TOTP Secret</label>
                  <input
                    type="text"
                    value={config.scraper_settings.instagram?.totp_secret || ''}
                    onChange={e => updateScraperSettings('instagram', { totp_secret: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-slate-500 dark:text-slate-400 mb-1">Session File</label>
                  <input
                    type="text"
                    value={config.scraper_settings.instagram?.session_file || ''}
                    onChange={e => updateScraperSettings('instagram', { session_file: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-sm focus:ring-2 focus:ring-purple-500"
                  />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Paste Modal */}
      {showPasteModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl w-full max-w-md mx-4 p-5 space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="font-semibold text-slate-900 dark:text-slate-100">Paste Usernames</h3>
              <button onClick={() => { setShowPasteModal(false); setPasteText('') }} className="text-slate-400 hover:text-slate-600">
                <X className="w-5 h-5" />
              </button>
            </div>
            <p className="text-sm text-slate-500 dark:text-slate-400">
              Paste usernames separated by commas, semicolons, or new lines.
            </p>
            <textarea
              value={pasteText}
              onChange={e => setPasteText(e.target.value)}
              rows={8}
              autoFocus
              className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 font-mono text-sm focus:ring-2 focus:ring-purple-500"
              placeholder="username1&#10;username2&#10;username3"
            />
            <div className="flex justify-end space-x-2">
              <button
                onClick={() => { setShowPasteModal(false); setPasteText('') }}
                className="px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-200 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handlePaste}
                className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm font-medium transition-colors"
              >
                Add Usernames
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
})

export default InstagramUnified
