'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { RefreshCw, ArrowLeft, Loader2, CheckCircle2, AlertTriangle, Shield, Users, Smartphone, ScrollText, Layers, AppWindow, ChevronDown, ChevronUp, ShieldOff, ShieldAlert, ShieldX } from 'lucide-react';

interface DuoStatus {
  connected: boolean;
  syncing: boolean;
  lastSync: string | null;
  counts: {
    accounts: number;
    users: number;
    phones: number;
    authLogs: number;
    groups: number;
    integrations: number;
    bypass: number;
    disabled: number;
  };
}

interface FlaggedUser {
  user_id: string;
  username: string;
  email: string | null;
  realname: string | null;
  status: string;
  is_enrolled: boolean;
  last_login: string | null;
  notes: string | null;
  account_name: string;
}

interface DuoAccount {
  id: number;
  account_id: string;
  name: string;
  api_hostname: string;
  user_count: number;
  integration_count: number;
  is_parent: boolean;
  synced_at: string | null;
  autotask_company_id: string | null;
  autotask_company_name: string | null;
}

export default function DuoSyncPage() {
  const [status, setStatus] = useState<DuoStatus | null>(null);
  const [accounts, setAccounts] = useState<DuoAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);
  const [bypassUsers, setBypassUsers] = useState<FlaggedUser[]>([]);
  const [disabledUsers, setDisabledUsers] = useState<FlaggedUser[]>([]);
  const [showBypass, setShowBypass] = useState(false);
  const [showDisabled, setShowDisabled] = useState(false);

  const fetchData = async () => {
    try {
      const [statusRes, accountsRes, flaggedRes] = await Promise.all([
        fetch('/api/duo/status'),
        fetch('/api/duo/accounts'),
        fetch('/api/duo/users/flagged'),
      ]);
      if (statusRes.ok) setStatus(await statusRes.json());
      if (accountsRes.ok) {
        const d = await accountsRes.json();
        setAccounts(d.accounts ?? []);
      }
      if (flaggedRes.ok) {
        const d = await flaggedRes.json();
        setBypassUsers(d.bypass ?? []);
        setDisabledUsers(d.disabled ?? []);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

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

  const triggerSync = async () => {
    setSyncing(true);
    try {
      await fetch('/api/duo/sync', { method: 'POST' });
      // Poll for completion
      const poll = setInterval(async () => {
        const r = await fetch('/api/duo/sync');
        if (r.ok) {
          const d = await r.json();
          if (!d.inProgress) {
            clearInterval(poll);
            setSyncing(false);
            fetchData();
          }
        }
      }, 5000);
    } catch (e) {
      console.error(e);
      setSyncing(false);
    }
  };

  const fmtDate = (d: string | null) => {
    if (!d) return 'Never';
    return new Date(d).toLocaleString();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const childAccounts = accounts.filter(a => !a.is_parent);
  const parentAccount = accounts.find(a => a.is_parent);

  return (
    <div className="container mx-auto py-4 md:py-8 px-4 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/sync">
            <Button variant="ghost" size="icon"><ArrowLeft className="w-4 h-4" /></Button>
          </Link>
          <div className="flex items-center gap-3">
            <img src="/logos/duo.ico" alt="Duo" className="w-8 h-8 rounded" />
            <div>
              <h1 className="text-2xl font-bold">Duo Security</h1>
              <p className="text-sm text-muted-foreground">2FA / MFA — Accounts & Admin API sync</p>
            </div>
          </div>
        </div>
        <Button onClick={triggerSync} disabled={syncing} className="gap-2">
          {syncing ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
          {syncing ? 'Syncing...' : 'Sync Now'}
        </Button>
      </div>

      {/* Status cards */}
      {status && (
        <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3">
          <StatCard icon={<Shield className="w-4 h-4" />} label="Accounts" value={status.counts.accounts} />
          <StatCard icon={<Users className="w-4 h-4" />} label="Users" value={status.counts.users} />
          <StatCard icon={<Smartphone className="w-4 h-4" />} label="Phones" value={status.counts.phones} />
          <StatCard icon={<ScrollText className="w-4 h-4" />} label="Auth Logs" value={status.counts.authLogs} />
          <StatCard icon={<Layers className="w-4 h-4" />} label="Groups" value={status.counts.groups} />
          <StatCard icon={<AppWindow className="w-4 h-4" />} label="Integrations" value={status.counts.integrations} />
        </div>
      )}

      {/* Last sync + warnings */}
      <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
        <span>Last sync: <strong className="text-foreground">{fmtDate(status?.lastSync ?? null)}</strong></span>
        {bypassUsers.length > 0 && (
          <button
            onClick={() => setShowBypass(!showBypass)}
            className="flex items-center gap-1 text-red-600 hover:text-red-500 transition-colors font-medium"
          >
            <ShieldAlert className="w-4 h-4" />
            {bypassUsers.length} user(s) in bypass — MFA not enforced
            {showBypass ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
          </button>
        )}
        {disabledUsers.length > 0 && (
          <button
            onClick={() => setShowDisabled(!showDisabled)}
            className="flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors"
          >
            <ShieldOff className="w-4 h-4" />
            {disabledUsers.length} disabled user(s)
            {showDisabled ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
          </button>
        )}
      </div>

      {/* Bypass users — security concern */}
      {showBypass && bypassUsers.length > 0 && (
        <FlaggedUsersTable
          title="Bypass Users — MFA Not Enforced"
          description="These users can authenticate without completing MFA. This is a security risk."
          users={bypassUsers}
          icon={<ShieldAlert className="w-4 h-4 text-red-600" />}
          borderColor="border-red-500/30"
          bgColor="bg-red-500/5"
          headerColor="text-red-700 dark:text-red-400"
          fmtDate={fmtDate}
        />
      )}

      {/* Disabled users — informational */}
      {showDisabled && disabledUsers.length > 0 && (
        <FlaggedUsersTable
          title="Disabled Users"
          description="These users are locked out and cannot authenticate. No action needed unless unexpected."
          users={disabledUsers}
          icon={<ShieldOff className="w-4 h-4 text-muted-foreground" />}
          borderColor="border-border"
          bgColor="bg-muted/5"
          headerColor="text-muted-foreground"
          fmtDate={fmtDate}
        />
      )}

      {/* Parent account */}
      {parentAccount && (
        <div className="rounded-lg border border-border p-4">
          <h2 className="text-sm font-semibold mb-2 flex items-center gap-2">
            <Shield className="w-4 h-4 text-blue-500" /> Parent Account
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
            <div><span className="text-muted-foreground">Name:</span> <strong>{parentAccount.name}</strong></div>
            <div><span className="text-muted-foreground">Users:</span> <strong>{parentAccount.user_count}</strong></div>
            <div><span className="text-muted-foreground">Integrations:</span> <strong>{parentAccount.integration_count}</strong></div>
            <div><span className="text-muted-foreground">Synced:</span> <strong>{fmtDate(parentAccount.synced_at)}</strong></div>
          </div>
        </div>
      )}

      {/* Child accounts table */}
      <div>
        <h2 className="text-lg font-semibold mb-3">Child Accounts ({childAccounts.length})</h2>
        <div className="rounded-lg border border-border overflow-hidden">
          <Table>
            <TableHeader className="bg-muted/50">
              <TableRow>
                <TableHead>Account name</TableHead>
                <TableHead className="text-right">Users</TableHead>
                <TableHead className="text-right">Integrations</TableHead>
                <TableHead>Matched company</TableHead>
                <TableHead>Last sync</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {childAccounts.map(a => (
                <TableRow key={a.account_id}>
                  <TableCell className="font-medium">{a.name}</TableCell>
                  <TableCell className="text-right num">{a.user_count}</TableCell>
                  <TableCell className="text-right num">{a.integration_count}</TableCell>
                  <TableCell>
                    {a.autotask_company_name ? (
                      <span className="flex items-center gap-1">
                        <CheckCircle2 className="w-3 h-3 text-emerald-500" />
                        {a.autotask_company_name}
                      </span>
                    ) : (
                      <span className="text-muted-foreground">—</span>
                    )}
                  </TableCell>
                  <TableCell className="text-muted-foreground num">{fmtDate(a.synced_at)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
}

function StatCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: number }) {
  return (
    <div className="rounded-lg border border-border p-3">
      <div className="flex items-center gap-2 text-muted-foreground mb-1">
        {icon}
        <span className="text-xs">{label}</span>
      </div>
      <div className="text-xl font-bold">{value.toLocaleString()}</div>
    </div>
  );
}

function FlaggedUsersTable({ title, description, users, icon, borderColor, bgColor, headerColor, fmtDate }: {
  title: string;
  description: string;
  users: FlaggedUser[];
  icon: React.ReactNode;
  borderColor: string;
  bgColor: string;
  headerColor: string;
  fmtDate: (d: string | null) => string;
}) {
  return (
    <div className={`rounded-lg border ${borderColor} ${bgColor} overflow-hidden`}>
      <div className={`px-4 py-3 border-b ${borderColor}`}>
        <div className="flex items-center gap-2">
          {icon}
          <h3 className={`text-sm font-semibold ${headerColor}`}>{title} ({users.length})</h3>
        </div>
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
      </div>
      <Table>
        <TableHeader className={bgColor}>
          <TableRow>
            <TableHead>User</TableHead>
            <TableHead>Email</TableHead>
            <TableHead>Account</TableHead>
            <TableHead className="text-center">Enrolled</TableHead>
            <TableHead>Last login</TableHead>
            <TableHead>Notes</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {users.map(u => (
            <TableRow key={u.user_id}>
              <TableCell>
                <div className="font-medium">{u.realname || u.username}</div>
                {u.realname && <div className="text-xs text-muted-foreground">{u.username}</div>}
              </TableCell>
              <TableCell className="text-muted-foreground">{u.email || '\u2014'}</TableCell>
              <TableCell>{u.account_name}</TableCell>
              <TableCell className="text-center">
                {u.is_enrolled
                  ? <CheckCircle2 className="w-4 h-4 text-emerald-500 mx-auto" />
                  : <span className="text-muted-foreground">No</span>
                }
              </TableCell>
              <TableCell className="text-muted-foreground num">{u.last_login ? fmtDate(u.last_login) : 'Never'}</TableCell>
              <TableCell className="text-muted-foreground text-xs max-w-[200px] truncate">{u.notes || '\u2014'}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
