'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import {
  LayoutDashboard,
  Shield,
  Crown,
  BookOpen,
  Database,
  Globe,
  Activity,
  Server,
  Cpu,
  FileText,
  LineChart,
  ExternalLink,
  Lock,
  Terminal,
  CheckCircle,
  XCircle,
  Loader2,
} from 'lucide-react';

import { SystemStatus } from '@/components/SystemStatus';
import { HealthChecker } from '@/components/HealthChecker';
import { ApplicationTester } from '@/components/ApplicationTester';
import { isDev, getProjectName, getAppVersion } from '@/utils/environment';

interface QuickLink {
  label: string;
  href?: string;
  external?: string;
  icon: typeof LayoutDashboard;
  color: string;
  description: string;
}

function getQuickLinks(): QuickLink[] {
  const apiBase = (process.env.NEXT_PUBLIC_API_BASE_URL || '').replace(/\/$/, '');
  const prismaUrl = process.env.NEXT_PUBLIC_PRISMA_STUDIO_URL;

  const links: QuickLink[] = [
    {
      label: 'User Dashboard',
      href: '/dashboard',
      icon: LayoutDashboard,
      color: 'text-blue-400 bg-blue-500/10 border-blue-500/20 hover:border-blue-500/40',
      description: 'Open the user interface',
    },
    {
      label: 'Admin Dashboard',
      href: '/admin/dashboard',
      icon: Shield,
      color: 'text-indigo-400 bg-indigo-500/10 border-indigo-500/20 hover:border-indigo-500/40',
      description: 'Open the admin interface',
    },
    {
      label: 'Super Admin Dashboard',
      href: '/super-admin/dashboard',
      icon: Crown,
      color: 'text-amber-400 bg-amber-500/10 border-amber-500/20 hover:border-amber-500/40',
      description: 'Open the super admin interface',
    },
  ];

  if (apiBase) {
    links.push(
      {
        label: 'Swagger',
        external: `${apiBase}/api`,
        icon: BookOpen,
        color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20 hover:border-emerald-500/40',
        description: 'Open API documentation',
      },
      {
        label: 'API Health',
        external: `${apiBase}/health`,
        icon: Globe,
        color: 'text-cyan-400 bg-cyan-500/10 border-cyan-500/20 hover:border-cyan-500/40',
        description: 'Check API health endpoint',
      },
      {
        label: 'Database Status',
        external: `${apiBase}/health/database`,
        icon: Database,
        color: 'text-orange-400 bg-orange-500/10 border-orange-500/20 hover:border-orange-500/40',
        description: 'Check database connectivity',
      },
      {
        label: 'Redis Status',
        external: `${apiBase}/health/redis`,
        icon: Server,
        color: 'text-rose-400 bg-rose-500/10 border-rose-500/20 hover:border-rose-500/40',
        description: 'Check Redis connectivity',
      },
    );
  }

  if (prismaUrl) {
    links.push({
      label: 'Prisma Studio',
      external: prismaUrl,
      icon: Database,
      color: 'text-violet-400 bg-violet-500/10 border-violet-500/20 hover:border-violet-500/40',
      description: 'Open database explorer',
    });
  }

  links.push(
    {
      label: 'System Status',
      href: '/super-admin/developer',
      icon: Cpu,
      color: 'text-lime-400 bg-lime-500/10 border-lime-500/20 hover:border-lime-500/40',
      description: 'View system status panel below',
    },
    {
      label: 'Logs',
      href: '/super-admin/logs',
      icon: FileText,
      color: 'text-yellow-400 bg-yellow-500/10 border-yellow-500/20 hover:border-yellow-500/40',
      description: 'Open system logs',
    },
    {
      label: 'Monitoring',
      href: '/monitoring',
      icon: LineChart,
      color: 'text-pink-400 bg-pink-500/10 border-pink-500/20 hover:border-pink-500/40',
      description: 'Open monitoring dashboard',
    },
  );

  return links;
}

export default function DeveloperDashboardPage() {
  const router = useRouter();
  const [devMode, setDevMode] = useState<boolean | null>(null);

  useEffect(() => {
    setDevMode(isDev());
  }, []);

  if (devMode === false) {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="text-center">
          <Lock className="mx-auto h-12 w-12 text-slate-500" />
          <h2 className="mt-4 text-xl font-bold text-white">Developer Tools Unavailable</h2>
          <p className="mt-2 text-sm text-slate-400">
            Developer dashboard is only available in development mode.
          </p>
        </div>
      </div>
    );
  }

  if (devMode === null) {
    return (
      <div className="flex h-96 items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-slate-400" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-ink">Developer / System Control</h1>
          <p className="text-sm text-ink-muted">
            Internal diagnostics and system controls. Restricted to SUPER_ADMIN.
          </p>
        </div>
        <div className="flex items-center gap-2 text-xs text-ink-faint">
          <Lock className="h-4 w-4" />
          <span>SUPER_ADMIN only</span>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {getQuickLinks().map((link) => {
          if (link.external && !devMode) return null;
          const Icon = link.icon;
          return (
            <Link
              key={link.label}
              href={link.href ?? '#'}
              target={link.external ? '_blank' : undefined}
              rel={link.external ? 'noopener noreferrer' : undefined}
              className={`flex items-center gap-3 rounded-xl border p-4 transition-colors ${link.color}`}
            >
              <Icon className="h-5 w-5 shrink-0" />
              <div>
                <p className="text-sm font-medium">{link.label}</p>
                <p className="text-xs text-ink-muted">{link.description}</p>
              </div>
              {link.external && <ExternalLink className="ml-auto h-4 w-4 text-ink-faint" />}
            </Link>
          );
        })}
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        <SystemStatus />
        <HealthChecker />
      </div>

      <ApplicationTester />
    </div>
  );
}
