'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 } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
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;
    withOpenTicket: number;
    critical: number;
    high: number;
  };
  jobs: RpoJobSummary[];
}

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 [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  const fetchData = async () => {
    try {
      const [statusRes, companiesRes, complianceRes, rpoRes] = 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()),
      ]);
      setStatus(statusRes);
      setCompanies(Array.isArray(companiesRes) ? companiesRes : []);
      setCompliance(complianceRes);
      setRpo(rpoRes);
    } 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="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">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 className="w-full text-sm">
                    <thead>
                      <tr className="border-b bg-muted/50">
                        <th className="px-4 py-3 text-left font-medium">Job</th>
                        <th className="px-4 py-3 text-left font-medium">Organization</th>
                        <th className="px-4 py-3 text-left font-medium">Last Backup</th>
                        <th className="px-4 py-3 text-left font-medium">Status</th>
                        <th className="px-4 py-3 text-left font-medium">Ticket</th>
                        <th className="px-4 py-3 text-left font-medium">Failure Reason</th>
                      </tr>
                    </thead>
                    <tbody>
                      {rpo.jobs.map((job) => (
                        <tr key={job.job_instance_uid} className="border-b last:border-0 hover:bg-muted/30">
                          <td className="px-4 py-3 font-medium">{job.job_name}</td>
                          <td className="px-4 py-3 text-muted-foreground">{job.org_name}</td>
                          <td className="px-4 py-3 text-muted-foreground">{timeAgoHours(job.hours_since_backup)}</td>
                          <td className="px-4 py-3">
                            {job.is_breached ? (
                              <Badge variant="destructive">Breached</Badge>
                            ) : (
                              <Badge variant="outline" className="text-green-600 border-green-600">Healthy</Badge>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            {job.open_ticket ? (
                              <span className={`text-xs font-mono ${
                                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>
                            )}
                          </td>
                          <td className="px-4 py-3 text-xs text-muted-foreground max-w-xs truncate">
                            {job.failure_category ?? '—'}
                          </td>
                        </tr>
                      ))}
                      {rpo.jobs.length === 0 && (
                        <tr>
                          <td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">No workstation jobs found</td>
                        </tr>
                      )}
                    </tbody>
                  </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>
  );
}
