/**
 * TransactionTemplates Component - Predefined action templates
 */

import { useState, useEffect } from 'react'
import { useAdmin } from '../../contexts/AdminContext'
import { TransactionRequestStatus } from '../../types/admin'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import toast from 'react-hot-toast'

interface Template {
  id: string
  name: string
  description: string
  contractAddress: string
  functionName: string
  args: any[]
  category: 'maintenance' | 'emergency' | 'configuration'
}

const defaultTemplates: Template[] = [
  {
    id: 'pause_all',
    name: 'Pause All Contracts',
    description: 'Pause both MainnetTether and TransactionMirror',
    contractAddress: CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
    functionName: 'pause',
    args: [],
    category: 'emergency',
  },
  {
    id: 'unpause_all',
    name: 'Unpause All Contracts',
    description: 'Unpause both MainnetTether and TransactionMirror',
    contractAddress: CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
    functionName: 'unpause',
    args: [],
    category: 'maintenance',
  },
]

export default function TransactionTemplates() {
  const { createAdminAction } = useAdmin()
  const [templates, setTemplates] = useState<Template[]>(defaultTemplates)
  const [customTemplate, setCustomTemplate] = useState({
    name: '',
    description: '',
    contractAddress: '',
    functionName: '',
    args: '',
    category: 'maintenance' as const,
  })

  useEffect(() => {
    const stored = localStorage.getItem('admin_templates')
    if (stored) {
      const custom = JSON.parse(stored)
      setTemplates([...defaultTemplates, ...custom])
    }
  }, [])

  const saveCustomTemplate = () => {
    if (!customTemplate.name || !customTemplate.contractAddress || !customTemplate.functionName) {
      toast.error('Please fill in all required fields')
      return
    }

    try {
      const args = customTemplate.args ? JSON.parse(customTemplate.args) : []
      const newTemplate: Template = {
        id: `template_${Date.now()}`,
        name: customTemplate.name,
        description: customTemplate.description,
        contractAddress: customTemplate.contractAddress,
        functionName: customTemplate.functionName,
        args,
        category: customTemplate.category,
      }

      const updated = [...templates, newTemplate]
      setTemplates(updated)
      
      // Save custom templates
      const custom = updated.filter((t) => !defaultTemplates.find((dt) => dt.id === t.id))
      localStorage.setItem('admin_templates', JSON.stringify(custom))

      toast.success('Template saved')
      setCustomTemplate({
        name: '',
        description: '',
        contractAddress: '',
        functionName: '',
        args: '',
        category: 'maintenance',
      })
    } catch (error) {
      toast.error('Invalid JSON in args field')
    }
  }

  const executeTemplate = (template: Template) => {
    createAdminAction({
      type: template.functionName as any,
      contractAddress: template.contractAddress,
      functionName: template.functionName,
      args: template.args,
      status: TransactionRequestStatus.PENDING,
      createdAt: Date.now(),
      id: `template_${Date.now()}`,
    })
    toast.success(`Template "${template.name}" queued`)
  }

  const deleteTemplate = (id: string) => {
    if (defaultTemplates.find((t) => t.id === id)) {
      toast.error('Cannot delete default template')
      return
    }
    const updated = templates.filter((t) => t.id !== id)
    setTemplates(updated)
    const custom = updated.filter((t) => !defaultTemplates.find((dt) => dt.id === t.id))
    localStorage.setItem('admin_templates', JSON.stringify(custom))
    toast.success('Template deleted')
  }

  return (
    <div className="space-y-6">
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Transaction Templates</h2>
        <p className="text-white/70 text-sm mb-4">
          Create and use predefined templates for common admin operations.
        </p>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {templates.map((template) => (
            <div
              key={template.id}
              className="bg-white/5 rounded-lg p-4 border border-white/10"
            >
              <div className="flex justify-between items-start mb-2">
                <div className="flex-1">
                  <h3 className="text-white font-semibold mb-1">{template.name}</h3>
                  <p className="text-white/60 text-xs mb-2">{template.description}</p>
                  <span
                    className={`inline-block px-2 py-1 rounded text-xs ${
                      template.category === 'emergency'
                        ? 'bg-red-500/20 text-red-300'
                        : template.category === 'maintenance'
                        ? 'bg-blue-500/20 text-blue-300'
                        : 'bg-green-500/20 text-green-300'
                    }`}
                  >
                    {template.category}
                  </span>
                </div>
                {!defaultTemplates.find((t) => t.id === template.id) && (
                  <button
                    onClick={() => deleteTemplate(template.id)}
                    className="text-red-400 hover:text-red-300 text-sm"
                  >
                    ×
                  </button>
                )}
              </div>
              <button
                onClick={() => executeTemplate(template)}
                className="w-full mt-3 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
              >
                Use Template
              </button>
            </div>
          ))}
        </div>
      </div>

      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h3 className="text-lg font-bold text-white mb-4">Create Custom Template</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Template Name</label>
            <input
              type="text"
              value={customTemplate.name}
              onChange={(e) => setCustomTemplate({ ...customTemplate, name: e.target.value })}
              placeholder="My Custom Template"
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-white/70 text-sm mb-2">Description</label>
            <input
              type="text"
              value={customTemplate.description}
              onChange={(e) => setCustomTemplate({ ...customTemplate, description: e.target.value })}
              placeholder="What this template does"
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-white/70 text-sm mb-2">Contract Address</label>
            <input
              type="text"
              value={customTemplate.contractAddress}
              onChange={(e) => setCustomTemplate({ ...customTemplate, contractAddress: e.target.value })}
              placeholder="0x..."
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500 font-mono text-sm"
            />
          </div>
          <div>
            <label className="block text-white/70 text-sm mb-2">Function Name</label>
            <input
              type="text"
              value={customTemplate.functionName}
              onChange={(e) => setCustomTemplate({ ...customTemplate, functionName: e.target.value })}
              placeholder="pause"
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="block text-white/70 text-sm mb-2">Arguments (JSON array)</label>
            <input
              type="text"
              value={customTemplate.args}
              onChange={(e) => setCustomTemplate({ ...customTemplate, args: e.target.value })}
              placeholder='[] or ["0x..."]'
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500 font-mono text-sm"
            />
          </div>
          <div>
            <label className="block text-white/70 text-sm mb-2">Category</label>
            <select
              value={customTemplate.category}
              onChange={(e) => setCustomTemplate({ ...customTemplate, category: e.target.value as any })}
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-blue-500"
            >
              <option value="maintenance">Maintenance</option>
              <option value="emergency">Emergency</option>
              <option value="configuration">Configuration</option>
            </select>
          </div>
          <button
            onClick={saveCustomTemplate}
            className="w-full px-6 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg font-semibold transition-colors"
          >
            Save Template
          </button>
        </div>
      </div>
    </div>
  )
}
