'use client';

import { gql } from '@apollo/client';
import { useQuery as useApolloQuery } from '@apollo/client';
import { useQuery } from '@tanstack/react-query';
import { Server, Activity, AlertCircle, CheckCircle, Loader2, Building2, Layers3, ShieldCheck, Cpu } from 'lucide-react';
import Link from 'next/link';
import { useSession } from 'next-auth/react';

import { createCrossplaneClient, VM } from '@/lib/crossplane-client';
import { sessionHasItOpsRole } from '@/lib/it-ops-roles';

import { PhoenixHealthTile } from './dashboard/PhoenixHealthTile';
import { Badge } from './ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from './ui/Card';


interface ActivityItem {
  id: string;
  type: string;
  description: string;
  timestamp: Date;
}

const GET_RESOURCES = gql`
  query GetResources {
    resources {
      id
      name
      type
      status
    }
  }
`;

const GET_HEALTH = gql`
  query GetHealth {
    health {
      status
      timestamp
    }
  }
`;

const GET_WORKSPACE_CONTEXT = gql`
  query GetWorkspaceContext {
    myClient {
      id
      name
      status
      primaryDomain
    }
    mySubscriptions {
      id
      offerName
      commercialModel
      status
      fulfillmentMode
    }
    myEntitlements {
      id
      entitlementKey
      status
    }
  }
`;

export default function Dashboard() {
  const { data: session } = useSession();
  const crossplane = createCrossplaneClient(session?.accessToken as string);

  const { data: vms = [], isLoading: vmsLoading } = useQuery({
    queryKey: ['vms'],
    queryFn: () => crossplane.getVMs(),
  });

  const { data: resourcesData, loading: resourcesLoading } = useApolloQuery(GET_RESOURCES, {
    skip: !session,
  });

  const { data: healthData, loading: healthLoading } = useApolloQuery(GET_HEALTH, {
    skip: !session,
    pollInterval: 30000, // Refresh every 30 seconds
  });

  const { data: workspaceData, loading: workspaceLoading } = useApolloQuery(GET_WORKSPACE_CONTEXT, {
    skip: !session,
    errorPolicy: 'all',
  });

  const resources = resourcesData?.resources || [];
  const health = healthData?.health;
  const client = workspaceData?.myClient;
  const subscriptions = workspaceData?.mySubscriptions || [];
  const entitlements = workspaceData?.myEntitlements || [];
  const primarySubscription =
    subscriptions.find(
      (subscription: { status: string }) =>
        subscription.status === 'ACTIVE' || subscription.status === 'PENDING'
    ) || subscriptions[0];

  const runningVMs = vms.filter((vm: VM) => vm.status?.state === 'running').length;
  const stoppedVMs = vms.filter((vm: VM) => vm.status?.state === 'stopped').length;
  const totalVMs = vms.length;
  
  // Get recent activity from resources (last 10 created/updated)
  const recentActivity: ActivityItem[] = resources
    ?.slice(0, 10)
    .map((resource: { id: string; type: string; name: string; status: string; updatedAt?: string; createdAt?: string }) => ({
      id: resource.id,
      type: resource.type,
      description: `${resource.name} - ${resource.status}`,
      timestamp: new Date(resource.updatedAt || resource.createdAt || Date.now()),
    }))
    .sort((a: ActivityItem, b: ActivityItem) => b.timestamp.getTime() - a.timestamp.getTime()) || [];

  const showItOps = sessionHasItOpsRole(session?.roles);

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Dashboard</h1>

      {showItOps ? (
        <Card className="mb-8 border-orange-900/50 bg-orange-950/20">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-orange-200">IT operations</CardTitle>
            <Cpu className="h-4 w-4 text-orange-400" />
          </CardHeader>
          <CardContent className="flex flex-wrap items-center gap-4">
            <p className="text-sm text-muted-foreground">
              Live Proxmox inventory and IPAM drift (requires <code className="text-xs">IT_READ_API_URL</code> on the server).
            </p>
            <Link
              href="/it"
              className="inline-flex h-9 items-center rounded-md bg-orange-600 px-4 text-sm font-medium text-white hover:bg-orange-500"
            >
              Open /it
            </Link>
          </CardContent>
        </Card>
      ) : null}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Client Boundary</CardTitle>
            <Building2 className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            {workspaceLoading ? (
              <Loader2 className="h-6 w-6 animate-spin" />
            ) : (
              <>
                <div className="text-xl font-bold">{client?.name || session?.clientId || 'Pending'}</div>
                <p className="text-xs text-muted-foreground">
                  {client?.primaryDomain || 'Client record will appear here once the backend migration is live.'}
                </p>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Badge variant="outline">{client?.status || 'SESSION_ONLY'}</Badge>
                  {session?.tenantId ? <Badge variant="outline">Tenant {session.tenantId}</Badge> : null}
                </div>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Active Subscription</CardTitle>
            <Layers3 className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            {workspaceLoading ? (
              <Loader2 className="h-6 w-6 animate-spin" />
            ) : (
              <>
                <div className="text-xl font-bold">{primarySubscription?.offerName || 'No active subscription yet'}</div>
                <p className="text-xs text-muted-foreground">
                  {primarySubscription
                    ? `${primarySubscription.commercialModel} • ${primarySubscription.fulfillmentMode}`
                    : session?.subscriptionId || 'Subscription context will appear here after activation.'}
                </p>
                <div className="mt-3 flex flex-wrap gap-2">
                  {primarySubscription?.status ? <Badge variant="outline">{primarySubscription.status}</Badge> : null}
                  {session?.subscriptionId ? (
                    <Badge variant="outline">Session {session.subscriptionId}</Badge>
                  ) : null}
                </div>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Entitlements</CardTitle>
            <ShieldCheck className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            {workspaceLoading ? (
              <Loader2 className="h-6 w-6 animate-spin" />
            ) : (
              <>
                <div className="text-2xl font-bold">{entitlements.length}</div>
                <p className="text-xs text-muted-foreground">
                  {entitlements.length > 0
                    ? entitlements
                        .slice(0, 2)
                        .map((entitlement: { entitlementKey: string }) => entitlement.entitlementKey)
                        .join(', ')
                    : 'No entitlements returned yet for this workspace.'}
                </p>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Badge variant="outline">{session?.roles?.[0] || 'NO_ROLE'}</Badge>
                  <Badge variant="outline">{`${subscriptions.length} subscriptions`}</Badge>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total VMs</CardTitle>
            <Server className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{vmsLoading ? '...' : totalVMs}</div>
            <p className="text-xs text-muted-foreground">Across all sites</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Running</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{vmsLoading ? '...' : runningVMs}</div>
            <p className="text-xs text-muted-foreground">Active virtual machines</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Stopped</CardTitle>
            <AlertCircle className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{vmsLoading ? '...' : stoppedVMs}</div>
            <p className="text-xs text-muted-foreground">Inactive virtual machines</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">System Health</CardTitle>
            <Activity className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            {healthLoading ? (
              <Loader2 className="h-6 w-6 animate-spin" />
            ) : (
              <>
                <div className="text-2xl font-bold">
                  {health?.status === 'ok' ? 'Healthy' : health?.status || 'Unknown'}
                </div>
                <p className="text-xs text-muted-foreground">
                  {health?.status === 'ok' ? 'All systems operational' : 'Checking system status...'}
                </p>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        <PhoenixHealthTile />
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Recent Activity</CardTitle>
        </CardHeader>
        <CardContent>
          {resourcesLoading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : recentActivity.length === 0 ? (
            <p className="text-sm text-muted-foreground">No recent activity</p>
          ) : (
            <div className="space-y-3">
              {recentActivity.map((activity) => (
                <div key={activity.id} className="flex items-center justify-between border-b pb-2">
                  <div>
                    <p className="text-sm font-medium">{activity.description}</p>
                    <p className="text-xs text-muted-foreground">
                      {activity.timestamp.toLocaleString()}
                    </p>
                  </div>
                  <Badge variant="outline">{activity.type}</Badge>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
