'use client'

import { useState } from 'react'
import {
  Plus,
  Edit2,
  Trash2,
  Play,
  Pause,
  AlertCircle,
  AlertTriangle,
  Info,
  Zap,
  Loader2,
  Wand2
} from 'lucide-react'
import {
  useErrorRules,
  useCreateErrorRule,
  useUpdateErrorRule,
  useDeleteErrorRule
} from '@/hooks/use-enterprise-clients'
import { seedDefaultErrorRules } from '@/lib/api/admin'
import type { ErrorSeverity, ErrorDetectionRule } from '@/types/api'

interface EnterpriseErrorRulesManagerProps {
  clientId: string
}

interface RuleFormData {
  name: string
  pattern: string
  severity: ErrorSeverity
  description: string
}

const SEVERITY_CONFIG: Record<ErrorSeverity, { icon: React.ElementType; color: string; bg: string }> = {
  INFO: { icon: Info, color: 'text-blue-600', bg: 'bg-blue-100' },
  WARNING: { icon: AlertTriangle, color: 'text-yellow-600', bg: 'bg-yellow-100' },
  ERROR: { icon: AlertCircle, color: 'text-red-600', bg: 'bg-red-100' },
  CRITICAL: { icon: Zap, color: 'text-purple-600', bg: 'bg-purple-100' },
}

export function EnterpriseErrorRulesManager({ clientId }: EnterpriseErrorRulesManagerProps) {
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [editingRule, setEditingRule] = useState<string | null>(null)
  const [formData, setFormData] = useState<RuleFormData>({
    name: '',
    pattern: '',
    severity: 'WARNING',
    description: '',
  })
  const [patternError, setPatternError] = useState<string | null>(null)
  const [seeding, setSeeding] = useState(false)

  const { data: rules, isLoading, refetch } = useErrorRules(clientId)
  const createRule = useCreateErrorRule()
  const updateRule = useUpdateErrorRule()
  const deleteRule = useDeleteErrorRule()

  const validatePattern = (pattern: string): boolean => {
    try {
      new RegExp(pattern)
      setPatternError(null)
      return true
    } catch (e) {
      setPatternError((e as Error).message)
      return false
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!validatePattern(formData.pattern)) {
      return
    }

    try {
      if (editingRule) {
        await updateRule.mutateAsync({
          clientId,
          ruleId: editingRule,
          data: formData,
        })
      } else {
        await createRule.mutateAsync({
          clientId,
          data: formData,
        })
      }
      resetForm()
    } catch (error) {
      console.error('Failed to save rule:', error)
    }
  }

  const resetForm = () => {
    setFormData({ name: '', pattern: '', severity: 'WARNING', description: '' })
    setShowCreateForm(false)
    setEditingRule(null)
    setPatternError(null)
  }

  const handleEdit = (rule: ErrorDetectionRule) => {
    setFormData({
      name: rule.name,
      pattern: rule.pattern,
      severity: rule.severity,
      description: rule.description || '',
    })
    setEditingRule(rule.id)
    setShowCreateForm(true)
  }

  const handleToggleActive = async (ruleId: string, currentActive: boolean) => {
    try {
      await updateRule.mutateAsync({
        clientId,
        ruleId,
        data: { isActive: !currentActive },
      })
    } catch (error) {
      console.error('Failed to toggle rule:', error)
    }
  }

  const handleDelete = async (ruleId: string) => {
    if (!confirm('Are you sure you want to delete this rule? All detected errors for this rule will also be deleted.')) {
      return
    }

    try {
      await deleteRule.mutateAsync({ clientId, ruleId })
    } catch (error) {
      console.error('Failed to delete rule:', error)
    }
  }

  const handleSeedDefaults = async () => {
    setSeeding(true)
    try {
      const result = await seedDefaultErrorRules(clientId)
      if (result.count > 0) {
        refetch()
      }
    } catch (error) {
      console.error('Failed to seed default rules:', error)
    } finally {
      setSeeding(false)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-32">
        <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          {rules?.length || 0} rule{rules?.length !== 1 ? 's' : ''} configured
        </p>
        <div className="flex items-center gap-2">
          {(!rules || rules.length === 0) && (
            <button
              onClick={handleSeedDefaults}
              disabled={seeding}
              className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
            >
              {seeding ? (
                <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              ) : (
                <Wand2 className="h-4 w-4 mr-1" />
              )}
              Add Default Rules
            </button>
          )}
          <button
            onClick={() => setShowCreateForm(true)}
            className="inline-flex items-center px-3 py-1.5 border border-transparent rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
          >
            <Plus className="h-4 w-4 mr-1" />
            Add Rule
          </button>
        </div>
      </div>

      {/* Create/Edit Form */}
      {showCreateForm && (
        <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
          <h3 className="text-sm font-medium text-gray-900 mb-3">
            {editingRule ? 'Edit Rule' : 'Create New Rule'}
          </h3>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Name *
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  required
                  placeholder="e.g., Database Error"
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Severity
                </label>
                <select
                  value={formData.severity}
                  onChange={(e) => setFormData({ ...formData, severity: e.target.value as ErrorSeverity })}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm"
                >
                  <option value="INFO">Info</option>
                  <option value="WARNING">Warning</option>
                  <option value="ERROR">Error</option>
                  <option value="CRITICAL">Critical</option>
                </select>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Pattern (Regex) *
              </label>
              <input
                type="text"
                value={formData.pattern}
                onChange={(e) => {
                  setFormData({ ...formData, pattern: e.target.value })
                  validatePattern(e.target.value)
                }}
                required
                placeholder="e.g., \b(error|ERROR)\b"
                className={`w-full border rounded-md px-3 py-2 text-sm font-mono ${
                  patternError ? 'border-red-300 focus:ring-red-500' : 'border-gray-300'
                }`}
              />
              {patternError && (
                <p className="mt-1 text-xs text-red-600">{patternError}</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description
              </label>
              <input
                type="text"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="What does this rule detect?"
                className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm"
              />
            </div>
            <div className="flex items-center justify-end gap-2">
              <button
                type="button"
                onClick={resetForm}
                className="px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={createRule.isPending || updateRule.isPending}
                className="px-3 py-1.5 border border-transparent rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
              >
                {createRule.isPending || updateRule.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : editingRule ? (
                  'Update Rule'
                ) : (
                  'Create Rule'
                )}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Rules List */}
      {rules && rules.length > 0 ? (
        <div className="space-y-2">
          {rules.map((rule) => {
            const config = SEVERITY_CONFIG[rule.severity]
            const Icon = config.icon

            return (
              <div
                key={rule.id}
                className={`bg-white border rounded-lg p-4 ${
                  !rule.isActive ? 'opacity-60' : ''
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-start gap-3">
                    <div className={`p-2 rounded-lg ${config.bg}`}>
                      <Icon className={`h-4 w-4 ${config.color}`} />
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <h4 className="font-medium text-gray-900">{rule.name}</h4>
                        <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${config.bg} ${config.color}`}>
                          {rule.severity}
                        </span>
                        {!rule.isActive && (
                          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600">
                            Disabled
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-gray-500 mt-1 font-mono">
                        {rule.pattern}
                      </p>
                      {rule.description && (
                        <p className="text-sm text-gray-500 mt-1">
                          {rule.description}
                        </p>
                      )}
                      <p className="text-xs text-gray-400 mt-1">
                        {rule._count?.detectedErrors || 0} errors detected
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => handleToggleActive(rule.id, rule.isActive)}
                      className={`p-1.5 rounded ${
                        rule.isActive
                          ? 'text-gray-400 hover:text-yellow-600'
                          : 'text-gray-400 hover:text-green-600'
                      }`}
                      title={rule.isActive ? 'Disable' : 'Enable'}
                    >
                      {rule.isActive ? (
                        <Pause className="h-4 w-4" />
                      ) : (
                        <Play className="h-4 w-4" />
                      )}
                    </button>
                    <button
                      onClick={() => handleEdit(rule)}
                      className="p-1.5 text-gray-400 hover:text-blue-600 rounded"
                      title="Edit"
                    >
                      <Edit2 className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(rule.id)}
                      className="p-1.5 text-gray-400 hover:text-red-600 rounded"
                      title="Delete"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      ) : !showCreateForm ? (
        <div className="text-center py-8 text-gray-500">
          <AlertCircle className="h-8 w-8 mx-auto mb-2 opacity-50" />
          <p>No error detection rules configured</p>
          <p className="text-sm mt-1">
            Add rules to detect errors in container logs
          </p>
        </div>
      ) : null}
    </div>
  )
}
