'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import {
  Shield,
  Plus,
  RefreshCw,
  Clock,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  MoreVertical,
  Eye,
  RotateCcw,
  Trash2,
  FileText,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type { SubmissionStatus } from '@/lib/a2p-types';
import { formatStatus, getStatusColor, formatUseCase } from '@/lib/a2p-types';

interface A2PRegistration {
  id: string;
  business_name: string;
  status: SubmissionStatus;
  brand_trust_score: number | null;
  failure_reason: string | null;
  attempt_count: number;
  created_at: string;
  updated_at: string;
  input: {
    business: { businessName: string };
    campaign: { useCase: string };
  };
}

interface A2PStats {
  total: number;
  pending: number;
  approved: number;
  failed: number;
}

function StatusBadge({ status }: { status: SubmissionStatus }) {
  const color = getStatusColor(status);
  const colorMap: Record<string, string> = {
    green: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
    red: 'bg-red-500/10 text-red-400 border-red-500/20',
    yellow: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20',
    blue: 'bg-blue-500/10 text-blue-400 border-blue-500/20',
    amber: 'bg-amber-500/10 text-amber-400 border-amber-500/20',
    orange: 'bg-orange-500/10 text-orange-400 border-orange-500/20',
    slate: 'bg-slate-500/10 text-slate-400 border-slate-500/20',
  };

  return (
    <span className={cn(
      'inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium',
      colorMap[color] || colorMap.slate
    )}>
      {formatStatus(status)}
    </span>
  );
}

export default function A2PPage() {
  const [registrations, setRegistrations] = useState<A2PRegistration[]>([]);
  const [stats, setStats] = useState<A2PStats>({ total: 0, pending: 0, approved: 0, failed: 0 });
  const [loading, setLoading] = useState(true);
  const [actionMenuId, setActionMenuId] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch('/api/a2p?stats=true');
      const data = await res.json();
      setRegistrations(data.registrations || []);
      setStats(data.stats || { total: 0, pending: 0, approved: 0, failed: 0 });
    } catch (err) {
      console.error('Failed to fetch A2P data:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchData(); }, [fetchData]);

  async function handleRetry(id: string) {
    try {
      await fetch(`/api/a2p/${id}/retry`, { method: 'POST' });
      setActionMenuId(null);
      fetchData();
    } catch (err) {
      console.error('Retry failed:', err);
    }
  }

  async function handleDelete(id: string) {
    if (!confirm('Are you sure you want to delete this registration?')) return;
    try {
      await fetch(`/api/a2p/${id}`, { method: 'DELETE' });
      setActionMenuId(null);
      fetchData();
    } catch (err) {
      console.error('Delete failed:', err);
    }
  }

  const statCards = [
    {
      label: 'Total Registrations',
      value: stats.total,
      icon: FileText,
      color: 'text-cyan-400',
      bgColor: 'bg-cyan-500/10',
      borderColor: 'border-cyan-500/20',
    },
    {
      label: 'Pending',
      value: stats.pending,
      icon: Clock,
      color: 'text-yellow-400',
      bgColor: 'bg-yellow-500/10',
      borderColor: 'border-yellow-500/20',
    },
    {
      label: 'Approved',
      value: stats.approved,
      icon: CheckCircle2,
      color: 'text-emerald-400',
      bgColor: 'bg-emerald-500/10',
      borderColor: 'border-emerald-500/20',
    },
    {
      label: 'Failed',
      value: stats.failed,
      icon: XCircle,
      color: 'text-red-400',
      bgColor: 'bg-red-500/10',
      borderColor: 'border-red-500/20',
    },
  ];

  return (
    <div className="p-6 lg:p-8 space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-cyan-500/10 border border-cyan-500/20">
              <Shield className="h-5 w-5 text-cyan-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">A2P Registration</h1>
              <p className="text-sm text-slate-400">
                Manage 10DLC brand & campaign registrations
              </p>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={fetchData}
            className="flex items-center gap-2 rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-2.5 text-sm font-medium text-slate-300 hover:bg-slate-700/50 hover:text-white transition-colors"
          >
            <RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} />
            Refresh
          </button>
          <Link
            href="/a2p/register"
            className="flex items-center gap-2 rounded-lg bg-cyan-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-cyan-500 transition-colors shadow-lg shadow-cyan-600/20"
          >
            <Plus className="h-4 w-4" />
            New Registration
          </Link>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card) => {
          const Icon = card.icon;
          return (
            <div
              key={card.label}
              className={cn(
                'card rounded-xl border p-5',
                card.borderColor,
                'bg-slate-900/50'
              )}
            >
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-slate-400 font-medium">{card.label}</p>
                  <p className="mt-1 text-3xl font-bold text-white">{card.value}</p>
                </div>
                <div className={cn('flex h-12 w-12 items-center justify-center rounded-lg', card.bgColor)}>
                  <Icon className={cn('h-6 w-6', card.color)} />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Registration Table */}
      <div className="card rounded-xl border border-slate-800/60 bg-slate-900/50 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-800/60">
          <h2 className="text-lg font-semibold text-white">All Registrations</h2>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-16">
            <RefreshCw className="h-6 w-6 text-slate-500 animate-spin" />
            <span className="ml-3 text-slate-400">Loading registrations...</span>
          </div>
        ) : registrations.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-slate-800/50 mb-4">
              <Shield className="h-8 w-8 text-slate-600" />
            </div>
            <h3 className="text-lg font-medium text-slate-300 mb-1">No registrations yet</h3>
            <p className="text-sm text-slate-500 mb-6 max-w-sm">
              Create your first A2P 10DLC registration to start sending compliant business messages.
            </p>
            <Link
              href="/a2p/register"
              className="flex items-center gap-2 rounded-lg bg-cyan-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-cyan-500 transition-colors"
            >
              <Plus className="h-4 w-4" />
              Start Registration
            </Link>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-800/60">
                  <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Business Name
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Status
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Brand Score
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Use Case
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Created
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-800/40">
                {registrations.map((reg) => (
                  <tr key={reg.id} className="hover:bg-slate-800/30 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-white">
                        {reg.business_name}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <StatusBadge status={reg.status} />
                      {reg.failure_reason && (
                        <div className="mt-1 flex items-center gap-1 text-xs text-red-400/80">
                          <AlertTriangle className="h-3 w-3" />
                          <span className="truncate max-w-[200px]">{reg.failure_reason}</span>
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {reg.brand_trust_score != null ? (
                        <span className={cn(
                          'text-sm font-medium',
                          reg.brand_trust_score >= 75 ? 'text-emerald-400' :
                          reg.brand_trust_score >= 50 ? 'text-yellow-400' : 'text-red-400'
                        )}>
                          {reg.brand_trust_score}
                        </span>
                      ) : (
                        <span className="text-sm text-slate-600">—</span>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-sm text-slate-300">
                        {reg.input?.campaign?.useCase
                          ? formatUseCase(reg.input.campaign.useCase as Parameters<typeof formatUseCase>[0])
                          : '—'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="text-sm text-slate-400">
                        {new Date(reg.created_at).toLocaleDateString()}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right">
                      <div className="relative inline-block">
                        <button
                          onClick={() => setActionMenuId(actionMenuId === reg.id ? null : reg.id)}
                          className="rounded-lg p-2 text-slate-400 hover:text-white hover:bg-slate-700/50 transition-colors"
                        >
                          <MoreVertical className="h-4 w-4" />
                        </button>
                        {actionMenuId === reg.id && (
                          <div className="absolute right-0 top-full mt-1 z-20 w-44 rounded-lg border border-slate-700/50 bg-slate-800 py-1 shadow-xl">
                            <Link
                              href={`/a2p/register?edit=${reg.id}`}
                              className="flex items-center gap-2 px-3 py-2 text-sm text-slate-300 hover:text-white hover:bg-slate-700/50 transition-colors"
                              onClick={() => setActionMenuId(null)}
                            >
                              <Eye className="h-4 w-4" />
                              View Details
                            </Link>
                            {['brand_failed', 'campaign_failed', 'manual_review'].includes(reg.status) && (
                              <button
                                onClick={() => handleRetry(reg.id)}
                                className="flex w-full items-center gap-2 px-3 py-2 text-sm text-slate-300 hover:text-white hover:bg-slate-700/50 transition-colors"
                              >
                                <RotateCcw className="h-4 w-4" />
                                Retry
                              </button>
                            )}
                            <button
                              onClick={() => handleDelete(reg.id)}
                              className="flex w-full items-center gap-2 px-3 py-2 text-sm text-red-400 hover:text-red-300 hover:bg-red-500/10 transition-colors"
                            >
                              <Trash2 className="h-4 w-4" />
                              Delete
                            </button>
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
