import { useState } from 'react'
import { LifeBuoy, Shield, ShieldCheck, Play, Square, Clock, CheckCircle2, XCircle, Loader2 } from 'lucide-react'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { useSupportSession } from '@/hooks/useSupportSession'
import { t } from '@/lib/i18n'

const MODE_OPTIONS = [
  {
    value: 'provision' as const,
    labelKey: 'Provision',
    descriptionKey: 'Agent can only read and create new entities. Cannot modify or delete existing ones.',
    icon: Shield,
    color: 'text-green-600 bg-green-50 border-green-200',
  },
  {
    value: 'configure' as const,
    labelKey: 'Configure',
    descriptionKey: 'Agent can read, create, edit, and delete entities. Full CRUD access.',
    icon: ShieldCheck,
    color: 'text-blue-600 bg-blue-50 border-blue-200',
  },
]

export function Support() {
  const { session, loading, polling, commandLog, error, startSession, endSession } = useSupportSession()
  const [selectedMode, setSelectedMode] = useState<'provision' | 'configure'>('configure')

  const getTimeRemaining = () => {
    if (!session.expiresAt) return null
    const diff = new Date(session.expiresAt).getTime() - Date.now()
    if (diff <= 0) return t('Expired')
    const mins = Math.floor(diff / 60000)
    const secs = Math.floor((diff % 60000) / 1000)
    return `${mins}m ${secs}s`
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <PageHeader
        title={t('Remote Support')}
        subtitle={t('Enable remote management by the BoostBot support team')}
      />

      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700 text-sm">
          {error}
        </div>
      )}

      {!session.active ? (
        <>
          {/* Mode Selection */}
          <Card>
            <CardHeader>
              <CardTitle>{t('Access Level')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {MODE_OPTIONS.map((opt) => {
                  const Icon = opt.icon
                  const isSelected = selectedMode === opt.value
                  return (
                    <button
                      key={opt.value}
                      onClick={() => setSelectedMode(opt.value)}
                      className={`
                        w-full flex items-start gap-4 p-4 rounded-lg border-2 text-start transition-all
                        ${isSelected ? opt.color + ' ring-2 ring-offset-1' : 'bg-white border-gray-200 hover:border-gray-300'}
                      `}
                    >
                      <Icon className={`w-6 h-6 mt-0.5 flex-shrink-0 ${isSelected ? '' : 'text-gray-400'}`} />
                      <div className="flex-1">
                        <div className={`font-semibold ${isSelected ? '' : 'text-gray-700'}`}>{t(opt.labelKey)}</div>
                        <div className={`text-sm mt-0.5 ${isSelected ? 'opacity-80' : 'text-gray-500'}`}>
                          {t(opt.descriptionKey)}
                        </div>
                      </div>
                    </button>
                  )
                })}
              </div>

              <button
                onClick={() => startSession(selectedMode)}
                disabled={loading}
                className="mt-6 w-full flex items-center justify-center gap-2 px-6 py-3 bg-primary-600 text-white rounded-lg font-medium hover:bg-primary-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <Play className="w-5 h-5" />
                )}
                <span>{loading ? t('Connecting...') : t('Enable Remote Support')}</span>
              </button>
            </CardContent>
          </Card>

          {/* How it works */}
          <Card>
            <CardHeader>
              <CardTitle>{t('How It Works')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3 text-sm text-gray-600">
                <p>
                  {t('When you enable remote support, your site\'s configuration is securely shared with the BoostBot team. A support agent can then configure your chatbot remotely.')}
                </p>
                <p>
                  {t('All communication is initiated by your site (outgoing connections only). No inbound access to your server is needed.')}
                </p>
                <p>
                  {t('The session automatically expires after 30 minutes. You can end it manually at any time.')}
                </p>
              </div>
            </CardContent>
          </Card>
        </>
      ) : (
        <>
          {/* Active Session */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between w-full">
                <CardTitle className="flex items-center gap-2">
                  <LifeBuoy className="w-5 h-5 text-green-600" />
                  {t('Support Session Active')}
                </CardTitle>
                <div className="flex items-center gap-2 text-sm text-gray-500">
                  <Clock className="w-4 h-4" />
                  <span>{getTimeRemaining()}</span>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex items-center gap-4 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-gray-700">{t('Mode:')}</span>
                    <span className="px-2 py-0.5 bg-blue-50 text-blue-700 rounded text-xs font-medium uppercase">
                      {session.mode}
                    </span>
                  </div>
                  {polling && (
                    <div className="flex items-center gap-1 text-gray-400">
                      <Loader2 className="w-3 h-3 animate-spin" />
                      <span className="text-xs">{t('Listening...')}</span>
                    </div>
                  )}
                </div>

                <button
                  onClick={endSession}
                  disabled={loading}
                  className="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-700 rounded-lg font-medium hover:bg-red-100 transition-colors border border-red-200 disabled:opacity-50"
                >
                  {loading ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Square className="w-4 h-4" />
                  )}
                  <span>{t('End Session')}</span>
                </button>
              </div>
            </CardContent>
          </Card>

          {/* Command Activity Log */}
          <Card>
            <CardHeader>
              <CardTitle>{t('Activity Log')}</CardTitle>
            </CardHeader>
            <CardContent>
              {commandLog.length === 0 ? (
                <div className="text-center py-8 text-gray-400 text-sm">
                  {t('Waiting for commands from the support agent...')}
                </div>
              ) : (
                <div className="space-y-2 max-h-80 overflow-y-auto">
                  {commandLog.map((log, idx) => (
                    <div
                      key={idx}
                      className="flex items-center gap-3 px-3 py-2 rounded-lg bg-gray-50 text-sm"
                    >
                      {log.status === 'completed' ? (
                        <CheckCircle2 className="w-4 h-4 text-green-500 flex-shrink-0" />
                      ) : (
                        <XCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
                      )}
                      <div className="flex-1 min-w-0">
                        <span className="font-mono text-gray-700 truncate block">{log.actionId}</span>
                        {(log.method || log.endpoint) && (
                          <span className="text-xs text-gray-400 font-mono truncate block">
                            {log.method} {log.endpoint}
                          </span>
                        )}
                      </div>
                      <span className="text-xs text-gray-400 flex-shrink-0">
                        {new Date(log.timestamp).toLocaleTimeString()}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}
    </div>
  )
}
