import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect } from 'react'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../../config/breadcrumbConfig'
import {
  Settings,
  Save,
  FolderOpen,
  Clock,
  Download,
  Bell,
  Shield,
  RefreshCw,
  Tag,
  Plus,
  Trash2,
  Edit,
  X,
  Zap,
  Play,
  ToggleLeft,
  ToggleRight,
  Loader2,
} from 'lucide-react'
import { api, getErrorMessage, PaidContentSettings as SettingsType, PaidContentTag, PaidContentAutoTagRule, PaidContentCreator } from '../../lib/api'
import { notificationManager } from '../../lib/notificationManager'

// Predefined tag colors for easy selection
const TAG_COLORS = [
  '#f59e0b', // amber
  '#ef4444', // red
  '#10b981', // emerald
  '#3b82f6', // blue
  '#8b5cf6', // violet
  '#ec4899', // pink
  '#f97316', // orange
  '#06b6d4', // cyan
  '#84cc16', // lime
  '#6b7280', // gray
]

function TagsManagement() {
  const queryClient = useQueryClient()
  const [isAdding, setIsAdding] = useState(false)
  const [editingTag, setEditingTag] = useState<PaidContentTag | null>(null)
  const [newTagName, setNewTagName] = useState('')
  const [newTagColor, setNewTagColor] = useState(TAG_COLORS[0])

  const { data: tags = [], isLoading } = useQuery({
    queryKey: ['paid-content-tags'],
    queryFn: () => api.paidContent.getTags(),
  })

  const createMutation = useMutation({
    mutationFn: () => api.paidContent.createTag(newTagName, newTagColor),
    onSuccess: () => {
      notificationManager.success('Tag Created', `Tag "${newTagName}" has been created`)
      queryClient.invalidateQueries({ queryKey: ['paid-content-tags'] })
      setIsAdding(false)
      setNewTagName('')
      setNewTagColor(TAG_COLORS[0])
    },
    onError: (error: unknown) => {
      notificationManager.error('Create Failed', getErrorMessage(error))
    },
  })

  const updateMutation = useMutation({
    mutationFn: (data: { id: number; name: string; color: string; description?: string }) =>
      api.paidContent.updateTag(data.id, { name: data.name, color: data.color }),
    onSuccess: () => {
      notificationManager.success('Tag Updated', 'Tag has been updated')
      queryClient.invalidateQueries({ queryKey: ['paid-content-tags'] })
      setEditingTag(null)
    },
    onError: (error: unknown) => {
      notificationManager.error('Update Failed', getErrorMessage(error))
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (id: number) => api.paidContent.deleteTag(id),
    onSuccess: () => {
      notificationManager.success('Tag Deleted', 'Tag has been deleted')
      queryClient.invalidateQueries({ queryKey: ['paid-content-tags'] })
    },
    onError: (error: unknown) => {
      notificationManager.error('Delete Failed', getErrorMessage(error))
    },
  })

  const handleCreate = () => {
    if (!newTagName.trim()) return
    createMutation.mutate()
  }

  const handleUpdate = () => {
    if (!editingTag || !editingTag.name.trim()) return
    updateMutation.mutate({
      id: editingTag.id,
      name: editingTag.name,
      color: editingTag.color,
    })
  }

  const handleDelete = (tag: PaidContentTag) => {
    if (confirm(`Delete tag "${tag.name}"? This will remove it from all posts.`)) {
      deleteMutation.mutate(tag.id)
    }
  }

  return (
    <div className="bg-card rounded-xl border border-border p-4 md:p-6">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-foreground flex items-center">
          <Tag className="w-5 h-5 mr-2 text-violet-600 dark:text-violet-400" />
          Tags
        </h2>
        {!isAdding && (
          <button
            onClick={() => setIsAdding(true)}
            className="btn btn-sm btn-secondary"
          >
            <Plus className="w-4 h-4 mr-1" />
            Add Tag
          </button>
        )}
      </div>

      {/* Add new tag form */}
      {isAdding && (
        <div className="mb-4 p-4 bg-secondary/50 rounded-lg space-y-3">
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">Name</label>
            <input
              type="text"
              value={newTagName}
              onChange={(e) => setNewTagName(e.target.value)}
              placeholder="Tag name"
              className="input w-full"
              autoFocus
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">Color</label>
            <div className="flex flex-wrap gap-2">
              {TAG_COLORS.map((color) => (
                <button
                  key={color}
                  type="button"
                  onClick={() => setNewTagColor(color)}
                  className={`w-8 h-8 rounded-full border-2 transition-all ${
                    newTagColor === color ? 'border-foreground scale-110' : 'border-transparent'
                  }`}
                  style={{ backgroundColor: color }}
                />
              ))}
            </div>
          </div>
          <div className="flex items-center justify-between pt-2">
            <div className="flex items-center gap-2">
              <span className="text-sm text-muted-foreground">Preview:</span>
              <span
                className="px-3 py-1 rounded-full text-sm font-medium text-white"
                style={{ backgroundColor: newTagColor }}
              >
                {newTagName || 'Tag Name'}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => {
                  setIsAdding(false)
                  setNewTagName('')
                  setNewTagColor(TAG_COLORS[0])
                }}
                className="btn btn-sm btn-secondary"
              >
                Cancel
              </button>
              <button
                onClick={handleCreate}
                disabled={!newTagName.trim() || createMutation.isPending}
                className="btn btn-sm btn-primary"
              >
                {createMutation.isPending ? (
                  <RefreshCw className="w-4 h-4 mr-1 animate-spin" />
                ) : (
                  <Plus className="w-4 h-4 mr-1" />
                )}
                Create
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Existing tags list */}
      {isLoading ? (
        <div className="flex items-center justify-center h-24">
          <RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
        </div>
      ) : tags.length === 0 ? (
        <p className="text-sm text-muted-foreground text-center py-8">
          No tags yet. Create one to organize your posts.
        </p>
      ) : (
        <div className="space-y-2">
          {tags.map((tag) => (
            <div
              key={tag.id}
              className="flex items-center justify-between p-3 bg-secondary/30 rounded-lg"
            >
              {editingTag?.id === tag.id ? (
                // Edit mode
                <div className="flex-1 space-y-3">
                  <div className="flex items-center gap-3">
                    <input
                      type="text"
                      value={editingTag.name}
                      onChange={(e) => setEditingTag({ ...editingTag, name: e.target.value })}
                      className="input flex-1"
                    />
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {TAG_COLORS.map((color) => (
                      <button
                        key={color}
                        type="button"
                        onClick={() => setEditingTag({ ...editingTag, color })}
                        className={`w-6 h-6 rounded-full border-2 transition-all ${
                          editingTag.color === color ? 'border-foreground scale-110' : 'border-transparent'
                        }`}
                        style={{ backgroundColor: color }}
                      />
                    ))}
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setEditingTag(null)}
                      className="btn btn-sm btn-secondary"
                    >
                      <X className="w-4 h-4 mr-1" />
                      Cancel
                    </button>
                    <button
                      onClick={handleUpdate}
                      disabled={!editingTag.name.trim() || updateMutation.isPending}
                      className="btn btn-sm btn-primary"
                    >
                      {updateMutation.isPending ? (
                        <RefreshCw className="w-4 h-4 mr-1 animate-spin" />
                      ) : (
                        <Save className="w-4 h-4 mr-1" />
                      )}
                      Save
                    </button>
                  </div>
                </div>
              ) : (
                // View mode
                <>
                  <div className="flex items-center gap-3">
                    <span
                      className="px-3 py-1 rounded-full text-sm font-medium text-white"
                      style={{ backgroundColor: tag.color }}
                    >
                      {tag.name}
                    </span>
                    {tag.post_count !== undefined && tag.post_count > 0 && (
                      <span className="text-xs text-muted-foreground bg-secondary px-2 py-0.5 rounded">
                        {tag.post_count} {tag.post_count === 1 ? 'post' : 'posts'}
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => setEditingTag(tag)}
                      className="p-2 rounded-lg hover:bg-secondary transition-colors text-muted-foreground hover:text-foreground"
                      title="Edit tag"
                    >
                      <Edit className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(tag)}
                      disabled={deleteMutation.isPending}
                      className="p-2 rounded-lg hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors text-muted-foreground hover:text-red-600"
                      title="Delete tag"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

const PLATFORMS = ['onlyfans', 'fansly', 'patreon', 'youtube', 'pornhub', 'xhamster', 'tiktok', 'instagram', 'twitch']
const CONTENT_TYPES = ['image', 'video', 'audio']
const RESOLUTIONS = ['720p', '1080p', '1440p', '4k']

function AutoTagRulesManagement() {
  const queryClient = useQueryClient()
  const [isAdding, setIsAdding] = useState(false)
  const [editingRule, setEditingRule] = useState<PaidContentAutoTagRule | null>(null)
  const [formName, setFormName] = useState('')
  const [formPriority, setFormPriority] = useState(0)
  const [formTagIds, setFormTagIds] = useState<number[]>([])
  const [formConditions, setFormConditions] = useState<Record<string, any>>({})

  const { data: rules = [], isLoading } = useQuery({
    queryKey: ['paid-content-auto-tag-rules'],
    queryFn: () => api.paidContent.getAutoTagRules(),
  })

  const { data: tags = [] } = useQuery({
    queryKey: ['paid-content-tags'],
    queryFn: () => api.paidContent.getTags(),
  })

  const { data: creators = [] } = useQuery<PaidContentCreator[]>({
    queryKey: ['paid-content-creators'],
    queryFn: () => api.paidContent.getCreators(),
  })

  const createMutation = useMutation({
    mutationFn: (data: { name: string; conditions: Record<string, any>; tag_ids: number[]; priority: number }) =>
      api.paidContent.createAutoTagRule(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-auto-tag-rules'] })
      resetForm()
      notificationManager.success('Rule Created', 'Auto-tag rule has been created')
    },
    onError: (e: unknown) => notificationManager.error('Error', getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, updates }: { id: number; updates: any }) =>
      api.paidContent.updateAutoTagRule(id, updates),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-auto-tag-rules'] })
      resetForm()
      notificationManager.success('Rule Updated', 'Auto-tag rule has been updated')
    },
    onError: (e: unknown) => notificationManager.error('Error', getErrorMessage(e)),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: number) => api.paidContent.deleteAutoTagRule(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-auto-tag-rules'] })
      notificationManager.success('Rule Deleted', 'Auto-tag rule has been deleted')
    },
  })

  const runAllMutation = useMutation({
    mutationFn: () => api.paidContent.runAllAutoTagRules(),
    onSuccess: () => notificationManager.success('Rules Running', 'Auto-tag rules are being applied to existing posts'),
  })

  const runOneMutation = useMutation({
    mutationFn: (id: number) => api.paidContent.runAutoTagRule(id),
    onSuccess: () => notificationManager.success('Rule Running', 'Rule is being applied to existing posts'),
  })

  const toggleMutation = useMutation({
    mutationFn: ({ id, enabled }: { id: number; enabled: number }) =>
      api.paidContent.updateAutoTagRule(id, { enabled }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['paid-content-auto-tag-rules'] }),
  })

  const resetForm = () => {
    setIsAdding(false)
    setEditingRule(null)
    setFormName('')
    setFormPriority(0)
    setFormTagIds([])
    setFormConditions({})
  }

  const startEdit = (rule: PaidContentAutoTagRule) => {
    setEditingRule(rule)
    setIsAdding(true)
    setFormName(rule.name)
    setFormPriority(rule.priority)
    setFormTagIds(rule.tag_ids)
    setFormConditions(rule.conditions || {})
  }

  const handleSave = () => {
    if (!formName.trim() || formTagIds.length === 0) return
    const data = { name: formName, conditions: formConditions, tag_ids: formTagIds, priority: formPriority }
    if (editingRule) {
      updateMutation.mutate({ id: editingRule.id, updates: data })
    } else {
      createMutation.mutate(data)
    }
  }

  const conditionSummary = (conditions: Record<string, any>) => {
    const parts: string[] = []
    if (conditions.creator_id) {
      const c = creators.find(cr => cr.id === conditions.creator_id)
      parts.push(`Creator: ${c?.username || conditions.creator_id}`)
    }
    if (conditions.platform) parts.push(`Platform: ${conditions.platform}`)
    if (conditions.content_type) parts.push(`Type: ${conditions.content_type}`)
    if (conditions.min_resolution) parts.push(`Min: ${conditions.min_resolution}`)
    if (conditions.title_contains) parts.push(`Title: "${conditions.title_contains}"`)
    if (conditions.description_contains) parts.push(`Desc: "${conditions.description_contains}"`)
    return parts.length > 0 ? parts.join(' · ') : 'No conditions'
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
          <Zap className="w-5 h-5 text-amber-500" />
          Auto-Tag Rules
        </h2>
        <div className="flex gap-2">
          <button
            onClick={() => runAllMutation.mutate()}
            disabled={runAllMutation.isPending || rules.length === 0}
            className="btn btn-secondary text-sm"
          >
            {runAllMutation.isPending ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Play className="w-4 h-4 mr-1" />}
            Run All on Existing
          </button>
          <button onClick={() => { resetForm(); setIsAdding(true) }} className="btn btn-primary text-sm">
            <Plus className="w-4 h-4 mr-1" /> Add Rule
          </button>
        </div>
      </div>
      <p className="text-sm text-muted-foreground">
        Auto-tag rules automatically apply tags to new posts during sync based on conditions you define.
      </p>

      {/* Add/Edit Form */}
      {isAdding && (
        <div className="bg-card rounded-xl border border-border p-4 space-y-4">
          <h3 className="font-medium">{editingRule ? 'Edit Rule' : 'New Rule'}</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">Name</label>
              <input
                type="text"
                value={formName}
                onChange={e => setFormName(e.target.value)}
                placeholder="Rule name"
                className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Priority (higher = first)</label>
              <input
                type="number"
                value={formPriority}
                onChange={e => setFormPriority(parseInt(e.target.value) || 0)}
                className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">Tags to Apply</label>
            <div className="flex flex-wrap gap-2">
              {tags.map(tag => (
                <button
                  key={tag.id}
                  onClick={() => setFormTagIds(prev =>
                    prev.includes(tag.id) ? prev.filter(id => id !== tag.id) : [...prev, tag.id]
                  )}
                  className={`px-2 py-1 rounded-full text-xs font-medium border transition-colors ${
                    formTagIds.includes(tag.id)
                      ? 'border-transparent text-white'
                      : 'border-border text-muted-foreground hover:text-foreground'
                  }`}
                  style={formTagIds.includes(tag.id) ? { backgroundColor: tag.color } : {}}
                >
                  {tag.name}
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-2">Conditions (all must match)</label>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              <div>
                <label className="block text-xs text-muted-foreground mb-1">Creator</label>
                <select
                  value={formConditions.creator_id || ''}
                  onChange={e => setFormConditions(prev => {
                    const v = e.target.value ? parseInt(e.target.value) : undefined
                    if (!v) { const { creator_id, ...rest } = prev; return rest }
                    return { ...prev, creator_id: v }
                  })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                >
                  <option value="">Any creator</option>
                  {creators.map(c => (
                    <option key={c.id} value={c.id}>{c.username} ({c.platform})</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-xs text-muted-foreground mb-1">Platform</label>
                <select
                  value={formConditions.platform || ''}
                  onChange={e => setFormConditions(prev => {
                    if (!e.target.value) { const { platform, ...rest } = prev; return rest }
                    return { ...prev, platform: e.target.value }
                  })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                >
                  <option value="">Any platform</option>
                  {PLATFORMS.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs text-muted-foreground mb-1">Content Type</label>
                <select
                  value={formConditions.content_type || ''}
                  onChange={e => setFormConditions(prev => {
                    if (!e.target.value) { const { content_type, ...rest } = prev; return rest }
                    return { ...prev, content_type: e.target.value }
                  })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                >
                  <option value="">Any type</option>
                  {CONTENT_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs text-muted-foreground mb-1">Min Resolution</label>
                <select
                  value={formConditions.min_resolution || ''}
                  onChange={e => setFormConditions(prev => {
                    if (!e.target.value) { const { min_resolution, ...rest } = prev; return rest }
                    return { ...prev, min_resolution: e.target.value }
                  })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                >
                  <option value="">Any resolution</option>
                  {RESOLUTIONS.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs text-muted-foreground mb-1">Title Contains</label>
                <input
                  type="text"
                  value={formConditions.title_contains || ''}
                  onChange={e => setFormConditions(prev => {
                    if (!e.target.value) { const { title_contains, ...rest } = prev; return rest }
                    return { ...prev, title_contains: e.target.value }
                  })}
                  placeholder="case-insensitive"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-muted-foreground mb-1">Description Contains</label>
                <input
                  type="text"
                  value={formConditions.description_contains || ''}
                  onChange={e => setFormConditions(prev => {
                    if (!e.target.value) { const { description_contains, ...rest } = prev; return rest }
                    return { ...prev, description_contains: e.target.value }
                  })}
                  placeholder="case-insensitive"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm"
                />
              </div>
            </div>
          </div>

          <div className="flex gap-2 justify-end">
            <button onClick={resetForm} className="btn btn-secondary text-sm">Cancel</button>
            <button
              onClick={handleSave}
              disabled={!formName.trim() || formTagIds.length === 0 || createMutation.isPending || updateMutation.isPending}
              className="btn btn-primary text-sm"
            >
              <Save className="w-4 h-4 mr-1" />
              {editingRule ? 'Update' : 'Create'}
            </button>
          </div>
        </div>
      )}

      {/* Rules List */}
      {isLoading ? (
        <div className="flex items-center justify-center h-32">
          <div className="animate-spin rounded-full h-6 w-6 border-2 border-primary border-t-transparent" />
        </div>
      ) : rules.length === 0 ? (
        <div className="text-center py-8 text-muted-foreground">
          <Zap className="w-8 h-8 mx-auto mb-2 opacity-40" />
          <p>No auto-tag rules yet. Create one to get started.</p>
        </div>
      ) : (
        <div className="space-y-2">
          {rules.map(rule => (
            <div key={rule.id} className="bg-card rounded-xl border border-border p-4 flex items-center gap-4">
              <button
                onClick={() => toggleMutation.mutate({ id: rule.id, enabled: rule.enabled ? 0 : 1 })}
                className="flex-shrink-0"
                title={rule.enabled ? 'Disable' : 'Enable'}
              >
                {rule.enabled ? (
                  <ToggleRight className="w-8 h-8 text-emerald-500" />
                ) : (
                  <ToggleLeft className="w-8 h-8 text-muted-foreground" />
                )}
              </button>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className={`font-medium ${!rule.enabled ? 'text-muted-foreground' : ''}`}>{rule.name}</span>
                  <span className="text-xs text-muted-foreground">Priority: {rule.priority}</span>
                  <span className="text-xs text-muted-foreground">Matches: {rule.match_count}</span>
                </div>
                <p className="text-xs text-muted-foreground mt-0.5">{conditionSummary(rule.conditions)}</p>
                <div className="flex gap-1 mt-1 flex-wrap">
                  {rule.tag_ids.map(tid => {
                    const tag = tags.find(t => t.id === tid)
                    return tag ? (
                      <span key={tid} className="px-2 py-0.5 rounded-full text-xs text-white" style={{ backgroundColor: tag.color }}>
                        {tag.name}
                      </span>
                    ) : null
                  })}
                </div>
              </div>
              <div className="flex gap-1 flex-shrink-0">
                <button
                  onClick={() => runOneMutation.mutate(rule.id)}
                  disabled={runOneMutation.isPending}
                  className="p-1.5 rounded-lg hover:bg-secondary text-muted-foreground hover:text-foreground"
                  title="Run on existing posts"
                >
                  <Play className="w-4 h-4" />
                </button>
                <button
                  onClick={() => startEdit(rule)}
                  className="p-1.5 rounded-lg hover:bg-secondary text-muted-foreground hover:text-foreground"
                >
                  <Edit className="w-4 h-4" />
                </button>
                <button
                  onClick={() => { if (confirm('Delete this rule?')) deleteMutation.mutate(rule.id) }}
                  className="p-1.5 rounded-lg hover:bg-secondary text-muted-foreground hover:text-red-500"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}



type TabType = 'settings' | 'tags' | 'auto-tag-rules'

export default function PaidContentSettingsPage() {
  useBreadcrumb(breadcrumbConfig['/paid-content/settings'])

  const queryClient = useQueryClient()
  const [formData, setFormData] = useState<Partial<SettingsType>>({})
  const [hasChanges, setHasChanges] = useState(false)
  const [activeTab, setActiveTab] = useState<TabType>('settings')

  const { data: settings, isLoading: settingsLoading } = useQuery<SettingsType>({
    queryKey: ['paid-content-settings'],
    queryFn: () => api.paidContent.getSettings(),
  })

  // Services query removed - credentials now managed on Scrapers page
  const servicesLoading = false

  useEffect(() => {
    if (settings) {
      setFormData(settings)
    }
  }, [settings])

  const updateMutation = useMutation({
    mutationFn: (data: Partial<SettingsType>) => api.paidContent.updateSettings(data),
    onSuccess: () => {
      notificationManager.success('Settings Saved', 'Your settings have been updated')
      queryClient.invalidateQueries({ queryKey: ['paid-content-settings'] })
      setHasChanges(false)
    },
    onError: (error: unknown) => {
      notificationManager.error('Save Failed', getErrorMessage(error))
    },
  })

  const handleChange = (key: keyof SettingsType, value: any) => {
    setFormData((prev) => ({ ...prev, [key]: value }))
    setHasChanges(true)
  }

  const handleSave = () => {
    // Validate embed_quality when download_embeds is enabled
    if (formData.download_embeds && !formData.embed_quality) {
      // Set default if not specified
      updateMutation.mutate({ ...formData, embed_quality: 'best' })
    } else {
      updateMutation.mutate(formData)
    }
  }

  const isLoading = settingsLoading || servicesLoading

  const tabs = [
    { id: 'settings' as TabType, label: 'Settings', icon: Settings },
    { id: 'tags' as TabType, label: 'Tags', icon: Tag },
    { id: 'auto-tag-rules' as TabType, label: 'Auto-Tag Rules', icon: Zap },
  ]

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <Settings className="w-8 h-8 text-violet-500" />
            Configuration
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Configure Paid Content preferences
          </p>
        </div>
        {hasChanges && activeTab === 'settings' && (
          <button
            onClick={handleSave}
            disabled={updateMutation.isPending}
            className="btn btn-primary"
          >
            {updateMutation.isPending ? (
              <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Save className="w-4 h-4 mr-2" />
            )}
            Save Changes
          </button>
        )}
      </div>

      {/* Tab Navigation */}
      <div className="border-b border-border">
        <nav className="flex space-x-4" aria-label="Tabs">
          {tabs.map((tab) => {
            const Icon = tab.icon
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
                  activeTab === tab.id
                    ? 'border-violet-500 text-violet-600 dark:text-violet-400'
                    : 'border-transparent text-muted-foreground hover:text-foreground hover:border-border'
                }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
              </button>
            )
          })}
        </nav>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"></div>
        </div>
      ) : activeTab === 'tags' ? (
        <TagsManagement />
      ) : activeTab === 'auto-tag-rules' ? (
        <AutoTagRulesManagement />
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Service Authentication - managed on Scrapers page */}
          <div className="lg:col-span-2">
            <div className="bg-card rounded-xl border border-border p-4 md:p-6">
              <div className="flex items-center space-x-3">
                <Shield className="w-5 h-5 text-violet-600 dark:text-violet-400" />
                <div>
                  <h2 className="text-lg font-semibold text-foreground">Service Authentication</h2>
                  <p className="text-sm text-muted-foreground mt-1">
                    Platform credentials are now managed in one place.{' '}
                    <a href="/scrapers" className="text-primary hover:underline font-medium">
                      Go to Scrapers page →
                    </a>
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Storage Settings */}
          <div className="bg-card rounded-xl border border-border p-4 md:p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4 flex items-center">
              <FolderOpen className="w-5 h-5 mr-2 text-violet-600 dark:text-violet-400" />
              Storage
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Download Directory
                </label>
                <input
                  type="text"
                  value={formData.base_download_path || ''}
                  onChange={(e) => handleChange('base_download_path', e.target.value)}
                  className="input w-full"
                  placeholder="/paid-content"
                />
              </div>
              <div className="space-y-2">
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={Boolean(formData.organize_by_date ?? true)}
                    onChange={(e) => handleChange('organize_by_date', e.target.checked)}
                    className="rounded border-border"
                  />
                  <span className="text-sm text-foreground">Organize by date</span>
                </label>
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={Boolean(formData.organize_by_post ?? true)}
                    onChange={(e) => handleChange('organize_by_post', e.target.checked)}
                    className="rounded border-border"
                  />
                  <span className="text-sm text-foreground">Create post subfolders</span>
                </label>
              </div>
            </div>
          </div>

          {/* Download Settings */}
          <div className="bg-card rounded-xl border border-border p-4 md:p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4 flex items-center">
              <Download className="w-5 h-5 mr-2 text-violet-600 dark:text-violet-400" />
              Downloads
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Max Concurrent Downloads
                </label>
                <input
                  type="number"
                  min="1"
                  max="10"
                  value={formData.max_concurrent_downloads || 3}
                  onChange={(e) => handleChange('max_concurrent_downloads', parseInt(e.target.value))}
                  className="input w-full"
                />
              </div>
              <div className="space-y-2">
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={Boolean(formData.download_embeds ?? true)}
                    onChange={(e) => handleChange('download_embeds', e.target.checked)}
                    className="rounded border-border"
                  />
                  <span className="text-sm text-foreground">Download embedded videos</span>
                </label>
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={Boolean(formData.auto_retry_failed ?? true)}
                    onChange={(e) => handleChange('auto_retry_failed', e.target.checked)}
                    className="rounded border-border"
                  />
                  <span className="text-sm text-foreground">Auto-retry failed downloads</span>
                </label>
              </div>
              {formData.auto_retry_failed && (
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Max Retry Attempts
                  </label>
                  <input
                    type="number"
                    min="1"
                    max="10"
                    value={formData.retry_max_attempts || 3}
                    onChange={(e) => handleChange('retry_max_attempts', parseInt(e.target.value))}
                    className="input w-full"
                  />
                </div>
              )}
              {formData.download_embeds && (
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Embed Video Quality
                  </label>
                  <select
                    value={formData.embed_quality || 'best'}
                    onChange={(e) => handleChange('embed_quality', e.target.value)}
                    className="input w-full"
                  >
                    <option value="best">Best Available</option>
                    <option value="1080p">1080p</option>
                    <option value="720p">720p</option>
                    <option value="480p">480p</option>
                  </select>
                </div>
              )}
            </div>
          </div>

          {/* Schedule Settings */}
          <div className="bg-card rounded-xl border border-border p-4 md:p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4 flex items-center">
              <Clock className="w-5 h-5 mr-2 text-violet-600 dark:text-violet-400" />
              Schedule
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Check Interval (hours)
                </label>
                <input
                  type="number"
                  min="1"
                  max="168"
                  value={formData.check_interval_hours || 6}
                  onChange={(e) => handleChange('check_interval_hours', parseInt(e.target.value))}
                  className="input w-full"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  How often to check for new content from tracked creators
                </p>
              </div>
            </div>
          </div>

          {/* Notification Settings */}
          <div className="bg-card rounded-xl border border-border p-4 md:p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4 flex items-center">
              <Bell className="w-5 h-5 mr-2 text-violet-600 dark:text-violet-400" />
              Notifications
            </h2>
            <div className="space-y-4">
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={Boolean(formData.notifications_enabled ?? true)}
                  onChange={(e) => handleChange('notifications_enabled', e.target.checked)}
                  className="rounded border-border"
                />
                <span className="text-sm text-foreground">Enable in-app notifications</span>
              </label>
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={Boolean(formData.push_notifications_enabled ?? true)}
                  onChange={(e) => handleChange('push_notifications_enabled', e.target.checked)}
                  className="rounded border-border"
                />
                <span className="text-sm text-foreground">Enable push notifications</span>
              </label>
            </div>
          </div>

          {/* Duplicate Detection */}
          <div className="bg-card rounded-xl border border-border p-4 md:p-6 lg:col-span-2">
            <h2 className="text-lg font-semibold text-foreground mb-4 flex items-center">
              <Shield className="w-5 h-5 mr-2 text-violet-600 dark:text-violet-400" />
              Duplicate Detection
            </h2>
            <div className="space-y-4">
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={Boolean(formData.perceptual_duplicate_detection ?? true)}
                  onChange={(e) => handleChange('perceptual_duplicate_detection', e.target.checked)}
                  className="rounded border-border"
                />
                <span className="text-sm text-foreground">
                  Enable perceptual duplicate detection (uses image hashing to find similar images)
                </span>
              </label>
              {formData.perceptual_duplicate_detection && (
                <div className="max-w-xs">
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Similarity Threshold (Hamming Distance)
                  </label>
                  <input
                    type="range"
                    min="0"
                    max="20"
                    value={formData.perceptual_threshold || 12}
                    onChange={(e) => handleChange('perceptual_threshold', parseInt(e.target.value))}
                    className="w-full"
                  />
                  <div className="flex justify-between text-xs text-muted-foreground mt-1">
                    <span>Strict (0)</span>
                    <span className="font-medium">{formData.perceptual_threshold || 12}</span>
                    <span>Loose (20)</span>
                  </div>
                  <p className="text-xs text-muted-foreground mt-2">
                    Lower values require more exact matches. Recommended: 10-14
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
