'use client';

import { useEffect, useState } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { BackupSummaryCards } from '@/components/backup/backup-summary-cards';
import { CompanyBackupTable, CompanyBackupRow } from '@/components/backup/company-backup-table';
import { ComplianceSummaryCards } from '@/components/backup/compliance-summary-cards';
import { ComplianceDetailTable } from '@/components/backup/compliance-detail-table';
import { ContractCoverageTable } from '@/components/backup/contract-coverage-table';
import { RefreshCw, CheckCircle2, AlertTriangle, XCircle, Clock, WifiOff } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { StatusBadge } from '@/components/ui/status-badge';
import { RpoJobSummary } from '@/lib/services/veeam-rpo-service';

interface BackupStatusData {
  totalProtectedWorkloads: number;
  unprotectedWorkloads: number;
  successRate24h: number;
  failedJobs24h: number;
  warningJobs24h: number;
  totalBackupServerJobs: number;
  totalBackupAgentJobs: number;
  lastSyncAt: string | null;
}

interface RpoData {
  summary: {
    total: number;
    healthy: number;
    breached: number;
    offlineSuppressed: number;
    withOpenTicket: number;
    critical: number;
    high: number;
  };
  jobs: RpoJobSummary[];
}

interface OfflineLogRow {
  id: number;
  job_name: string;
  org_name: string;
  rmm_hostname: string;
  rmm_site_name: string;
  device_type_category: string;
  rmm_last_seen: string | null;
  hours_offline: number;
  backup_interval_hours: number;
  checked_at: string;
}

interface ComplianceData {
  summary: {
    totalContractedDevices: number;
    matchedDevices: number;
    contractedNotBackedUp: number;
    backedUpNotContracted: number;
    computedAt: string | null;
  };
  mismatches: any[];
}

function timeAgo(dateStr: string | null): string {
  if (!dateStr) return 'Never';
  const diff = Date.now() - new Date(dateStr).getTime();
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return 'Just now';
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  return `${Math.floor(hours / 24)}d ago`;
}

function timeAgoHours(hours: number | null): string {
  if (hours === null) return 'Never';
  if (hours < 1) return 'Just now';
  if (hours < 24) return `${Math.round(hours)}h ago`;
  return `${Math.round(hours / 24)}d ago`;
}

export default function BackupStatusPage() {
  const [status, setStatus] = useState<BackupStatusData | null>(null);
  const [companies, setCompanies] = useState<CompanyBackupRow[]>([]);
  const [compliance, setCompliance] = useState<ComplianceData | null>(null);
  const [rpo, setRpo] = useState<RpoData | null>(null);
  const [offlineLog, setOfflineLog] = useState<OfflineLogRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  const fetchData = async () => {
    try {
      const [statusRes, companiesRes, complianceRes, rpoRes, offlineLogRes] = await Promise.all([
        fetch('/api/veeam/backup-status').then(r => r.json()),
        fetch('/api/veeam/companies').then(r => r.json()),
        fetch('/api/veeam/compliance').then(r => r.json()),
        fetch('/api/veeam/rpo-check').then(r => r.json()),
        fetch('/api/veeam/rpo-offline-log?limit=200').then(r => r.json()),
      ]);
      setStatus(statusRes);
      setCompanies(Array.isArray(companiesRes) ? companiesRes : []);
      setCompliance(complianceRes);
      setRpo(rpoRes);
      setOfflineLog(offlineLogRes.rows ?? []);
    } catch (error) {
      console.error('Failed to fetch backup status:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSync = async () => {
    setSyncing(true);
    try {
      await fetch('/api/veeam/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ syncType: 'full' }),
      });
      // Poll for completion
      const poll = setInterval(async () => {
        const res = await fetch('/api/veeam/sync').then(r => r.json());
        if (!res.isSyncing) {
          clearInterval(poll);
          setSyncing(false);
          fetchData();
        }
      }, 3000);
      // Safety timeout
      setTimeout(() => {
        clearInterval(poll);
        setSyncing(false);
        fetchData();
      }, 120000);
    } catch {
      setSyncing(false);
    }
  };

  const isSyncStale = status?.lastSyncAt
    ? Date.now() - new Date(status.lastSyncAt).getTime() > 2 * 60 * 60 * 1000
    : true;

  if (loading) {
    return (
      <div className="container mx-auto px-6 py-6 space-y-6">
        <div className="grid gap-4 md:grid-cols-3 lg:grid-cols-5">
          {[...Array(5)].map((_, i) => <Skeleton key={i} className="h-24" />)}
        </div>
        <Skeleton className="h-96" />
      </div>
    );
  }

  return (
    <div>
      <div className="container mx-auto px-6 py-6 space-y-6">

        <Tabs defaultValue="overview" className="space-y-6">
          <div className="flex items-center justify-between">
            <TabsList>
              <TabsTrigger value="overview">Backup Overview</TabsTrigger>
              <TabsTrigger value="rpo">
                RPO Status
                {rpo && rpo.summary.breached > 0 && (
                  <Badge variant="destructive" className="ml-2 h-5 px-1.5 text-xs">
                    {rpo.summary.breached}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="offline-log">
                Offline Suppressed
                {rpo && (rpo.summary.offlineSuppressed ?? 0) > 0 && (
                  <Badge variant="secondary" className="ml-2 h-5 px-1.5 text-xs">
                    {rpo.summary.offlineSuppressed}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="compliance">
                Contract Compliance
                {compliance && (compliance.summary.contractedNotBackedUp > 0 || compliance.summary.backedUpNotContracted > 0) && (
                  <Badge variant="destructive" className="ml-2 h-5 px-1.5 text-xs">
                    {compliance.summary.contractedNotBackedUp + compliance.summary.backedUpNotContracted}
                  </Badge>
                )}
              </TabsTrigger>
            </TabsList>
            <div className="flex items-center gap-3">
              {status?.lastSyncAt && (
                <span className="text-sm text-muted-foreground">
                  Last sync: {timeAgo(status.lastSyncAt)}
                </span>
              )}
              <Button
                variant="outline"
                size="sm"
                onClick={handleSync}
                disabled={syncing}
              >
                <RefreshCw className={`h-4 w-4 mr-2 ${syncing ? 'animate-spin' : ''}`} />
                {syncing ? 'Syncing...' : 'Sync Now'}
              </Button>
            </div>
          </div>

          <TabsContent value="overview" className="space-y-6">
            {status && (
              <BackupSummaryCards
                totalProtectedWorkloads={status.totalProtectedWorkloads}
                successRate24h={status.successRate24h}
                failedJobs24h={status.failedJobs24h}
                warningJobs24h={status.warningJobs24h}
                totalBackupServerJobs={status.totalBackupServerJobs}
                totalBackupAgentJobs={status.totalBackupAgentJobs}
                lastSyncAt={status.lastSyncAt}
              />
            )}
            <CompanyBackupTable companies={companies} />
          </TabsContent>

          <TabsContent value="rpo" className="space-y-6">
            {rpo && (
              <>
                {/* Summary Cards */}
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                      <CardTitle className="text-sm font-medium">Healthy Jobs</CardTitle>
                      <CheckCircle2 className="h-4 w-4 text-green-500" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">{rpo.summary.healthy}</div>
                      <p className="text-xs text-muted-foreground">of {rpo.summary.total} total</p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                      <CardTitle className="text-sm font-medium">RPO Breached</CardTitle>
                      <XCircle className="h-4 w-4 text-destructive" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold text-destructive">{rpo.summary.breached}</div>
                      <p className="text-xs text-muted-foreground">{rpo.summary.withOpenTicket} with open ticket</p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                      <CardTitle className="text-sm font-medium">Critical</CardTitle>
                      <AlertTriangle className="h-4 w-4 text-destructive" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold text-destructive">{rpo.summary.critical}</div>
                      <p className="text-xs text-muted-foreground">{rpo.summary.high} high priority</p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                      <CardTitle className="text-sm font-medium">Offline Suppressed</CardTitle>
                      <WifiOff className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">{rpo.summary.offlineSuppressed ?? 0}</div>
                      <p className="text-xs text-muted-foreground">breached but device offline</p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                      <CardTitle className="text-sm font-medium">Compliance Rate</CardTitle>
                      <Clock className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {rpo.summary.total > 0 ? Math.round((rpo.summary.healthy / rpo.summary.total) * 100) : 0}%
                      </div>
                      <p className="text-xs text-muted-foreground">jobs within RPO window</p>
                    </CardContent>
                  </Card>
                </div>

                {/* Job Table */}
                <div className="rounded-md border">
                  <Table>
                    <TableHeader className="bg-muted/50">
                      <TableRow>
                        <TableHead>Job</TableHead>
                        <TableHead>Organization</TableHead>
                        <TableHead>Last Backup</TableHead>
                        <TableHead>RMM Device</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead>Ticket</TableHead>
                        <TableHead>Failure Reason</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {rpo.jobs.map((job) => (
                        <TableRow key={job.job_instance_uid}>
                          <TableCell className="font-medium">{job.job_name}</TableCell>
                          <TableCell className="text-muted-foreground">{job.org_name}</TableCell>
                          <TableCell className="text-muted-foreground num">{timeAgoHours(job.hours_since_backup)}</TableCell>
                          <TableCell className="text-xs">
                            {job.rmm_hostname ? (
                              <div>
                                <span className="num">{job.rmm_hostname}</span>
                                {job.is_offline_suppressed && (
                                  <div className="flex items-center gap-1 mt-0.5 text-muted-foreground">
                                    <WifiOff className="h-3 w-3" />
                                    <span>offline {timeAgo(job.rmm_last_seen)}</span>
                                  </div>
                                )}
                              </div>
                            ) : (
                              <span className="text-muted-foreground">—</span>
                            )}
                          </TableCell>
                          <TableCell>
                            {job.is_offline_suppressed ? (
                              <StatusBadge tone="neutral" className="gap-1">
                                <WifiOff className="h-3 w-3" />Offline
                              </StatusBadge>
                            ) : job.is_breached ? (
                              <StatusBadge tone="error">Breached</StatusBadge>
                            ) : (
                              <StatusBadge tone="ok">Healthy</StatusBadge>
                            )}
                          </TableCell>
                          <TableCell>
                            {job.open_ticket ? (
                              <span className={`text-xs num ${
                                job.open_ticket.priority_level === 'critical' ? 'text-destructive' :
                                job.open_ticket.priority_level === 'high' ? 'text-orange-500' : 'text-muted-foreground'
                              }`}>
                                {job.open_ticket.at_ticket_number} ({job.open_ticket.priority_level})
                              </span>
                            ) : (
                              <span className="text-xs text-muted-foreground">—</span>
                            )}
                          </TableCell>
                          <TableCell className="text-xs text-muted-foreground max-w-xs truncate">
                            {job.failure_category ?? '—'}
                          </TableCell>
                        </TableRow>
                      ))}
                      {rpo.jobs.length === 0 && (
                        <TableRow>
                          <TableCell colSpan={7} className="px-4 py-8 text-center text-muted-foreground">No workstation jobs found</TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </>
            )}
          </TabsContent>

          <TabsContent value="offline-log" className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Workstation backup jobs suppressed during the last RPO check because the device was offline longer than its backup interval.
              No Autotask ticket is created while the device is offline.
            </p>
            <div className="rounded-md border">
              <Table>
                <TableHeader className="bg-muted/50">
                  <TableRow>
                    <TableHead>Device</TableHead>
                    <TableHead>Job</TableHead>
                    <TableHead>Organization</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Last Seen</TableHead>
                    <TableHead>Offline</TableHead>
                    <TableHead>Checked</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {offlineLog.map((row) => (
                    <TableRow key={row.id}>
                      <TableCell className="num text-xs">{row.rmm_hostname}</TableCell>
                      <TableCell className="text-xs text-muted-foreground max-w-[180px] truncate">{row.job_name}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">{row.org_name}</TableCell>
                      <TableCell>
                        <Badge variant="outline" className="text-xs">{row.device_type_category}</Badge>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground num">{timeAgo(row.rmm_last_seen)}</TableCell>
                      <TableCell className="text-xs num">
                        {row.hours_offline >= 48
                          ? `${Math.round(row.hours_offline / 24)}d`
                          : `${Math.round(row.hours_offline)}h`}
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground num">{timeAgo(row.checked_at)}</TableCell>
                    </TableRow>
                  ))}
                  {offlineLog.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={7} className="px-4 py-8 text-center text-muted-foreground">No offline suppressions logged yet</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </TabsContent>

          <TabsContent value="compliance" className="space-y-6">
            {compliance && (
              <>
                <ComplianceSummaryCards
                  totalContractedDevices={compliance.summary.totalContractedDevices}
                  matchedDevices={compliance.summary.matchedDevices}
                  contractedNotBackedUp={compliance.summary.contractedNotBackedUp}
                  backedUpNotContracted={compliance.summary.backedUpNotContracted}
                />
                <Tabs defaultValue="coverage" className="space-y-4">
                  <TabsList className="h-8">
                    <TabsTrigger value="coverage" className="text-xs">Contract Coverage</TabsTrigger>
                    <TabsTrigger value="mismatches" className="text-xs">
                      Mismatches
                      {(compliance.summary.contractedNotBackedUp + compliance.summary.backedUpNotContracted) > 0 && (
                        <Badge variant="destructive" className="ml-1.5 h-4 px-1 text-[10px]">
                          {compliance.summary.contractedNotBackedUp + compliance.summary.backedUpNotContracted}
                        </Badge>
                      )}
                    </TabsTrigger>
                  </TabsList>
                  <TabsContent value="coverage">
                    <ContractCoverageTable />
                  </TabsContent>
                  <TabsContent value="mismatches">
                    <ComplianceDetailTable mismatches={compliance.mismatches} />
                  </TabsContent>
                </Tabs>
              </>
            )}
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
