'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from '@/lib/i18n';
import {
  Database,
  Download,
  Upload,
  HardDrive,
  Clock,
  CheckCircle2,
  XCircle,
  RefreshCw,
  Calendar,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { authFetch } from '@/lib/api';

interface BackupRecord {
  id: string;
  filename: string;
  size: number;
  status: string;
  createdAt: string;
}

const formatSize = (bytes: number) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};

export default function DatabaseBackup() {
  const { t } = useTranslation();
  const [backups, setBackups] = useState<BackupRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [restoreOpen, setRestoreOpen] = useState(false);
  const [selectedBackup, setSelectedBackup] = useState<BackupRecord | null>(null);
  const [autoBackup, setAutoBackup] = useState(false);
  const [backupFrequency, setBackupFrequency] = useState('daily');

  const fetchBackups = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/backup');
      if (res.ok) {
        const data = await res.json();
        setBackups(data.backups || []);
      }
    } catch (err) {
      console.error('Fetch backups error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const createBackup = async () => {
    setCreating(true);
    try {
      const res = await authFetch('/api/backup', {
        method: 'POST',
        body: JSON.stringify({ description: 'Manual backup' }),
      });
      if (res.ok) {
        const data = await res.json();
        console.log('Backup created:', data);
        fetchBackups();
      }
    } catch (err) {
      console.error('Create backup error:', err);
    } finally {
      setCreating(false);
    }
  };

  const downloadBackup = (backup: BackupRecord) => {
    // Create a simple JSON download with backup info
    const content = JSON.stringify({ backupId: backup.id, filename: backup.filename, date: backup.createdAt }, null, 2);
    const blob = new Blob([content], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `backup-info-${backup.id}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const restoreFromBackup = (backup: BackupRecord) => {
    setSelectedBackup(backup);
    setRestoreOpen(true);
  };

  const confirmRestore = async () => {
    if (!selectedBackup) return;
    try {
      const res = await authFetch('/api/backup', {
        method: 'PUT',
        body: JSON.stringify({ backupId: selectedBackup.id }),
      });
      if (res.ok) {
        const data = await res.json();
        // Restore successful
        console.log('Restore completed:', data);
      } else {
        console.error('Restore failed');
      }
    } catch (err) {
      console.error('Restore error:', err);
    }
    setRestoreOpen(false);
  };

  const lastBackup = backups.length > 0 ? backups[0] : null;

  return (
    <div className="space-y-6 animate-fade-in">
      <div>
        <h1 className="text-2xl font-bold">{t.nav.backup}</h1>
        <p className="text-sm text-muted-foreground">Manage database backups and restore points</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-emerald-100 dark:bg-emerald-900/30 flex items-center justify-center">
              <HardDrive className="w-5 h-5 text-emerald-600" />
            </div>
            <div>
              <p className="text-2xl font-bold">{backups.length}</p>
              <p className="text-xs text-muted-foreground">Total Backups</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
              <Clock className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-sm font-bold">
                {lastBackup ? new Date(lastBackup.createdAt).toLocaleDateString() : 'Never'}
              </p>
              <p className="text-xs text-muted-foreground">{t.backup.lastBackup}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center">
              <Database className="w-5 h-5 text-orange-600" />
            </div>
            <div>
              <p className="text-sm font-bold">
                {lastBackup ? formatSize(lastBackup.size) : 'N/A'}
              </p>
              <p className="text-xs text-muted-foreground">{t.backup.backupSize}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Create Backup */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Database className="w-4 h-4 text-emerald-600" /> {t.backup.createBackup}
          </CardTitle>
          <CardDescription>Create a new database backup with all data</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-3">
            <Button
              onClick={createBackup}
              disabled={creating}
              className="bg-emerald-600 hover:bg-emerald-700"
            >
              {creating ? (
                <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
              ) : (
                <Database className="w-4 h-4 mr-2" />
              )}
              {creating ? 'Creating...' : t.backup.createBackup}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Auto Backup Settings */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">{t.backup.scheduleBackup}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <Label className="text-sm">{t.backup.automaticBackup}</Label>
              <p className="text-xs text-muted-foreground">Enable scheduled automatic backups</p>
            </div>
            <Switch checked={autoBackup} onCheckedChange={setAutoBackup} />
          </div>
          {autoBackup && (
            <div className="space-y-1.5">
              <Label className="text-xs">Frequency</Label>
              <Select value={backupFrequency} onValueChange={setBackupFrequency}>
                <SelectTrigger className="w-[200px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="hourly">Every Hour</SelectItem>
                  <SelectItem value="daily">Daily</SelectItem>
                  <SelectItem value="weekly">Weekly</SelectItem>
                  <SelectItem value="monthly">Monthly</SelectItem>
                </SelectContent>
              </Select>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Backup History */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">{t.backup.backupHistory}</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">{t.common.loading}</div>
          ) : backups.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">{t.common.noData}</div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-xs">Filename</TableHead>
                    <TableHead className="text-xs">{t.backup.backupSize}</TableHead>
                    <TableHead className="text-xs">Status</TableHead>
                    <TableHead className="text-xs">Date</TableHead>
                    <TableHead className="text-xs">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {backups.map((backup) => (
                    <TableRow key={backup.id}>
                      <TableCell className="text-xs font-mono max-w-[200px] truncate">{backup.filename}</TableCell>
                      <TableCell className="text-xs">{formatSize(backup.size)}</TableCell>
                      <TableCell>
                        <Badge
                          variant={backup.status === 'completed' ? 'default' : backup.status === 'failed' ? 'destructive' : 'secondary'}
                          className="text-[10px]"
                        >
                          {backup.status === 'completed' && <CheckCircle2 className="w-3 h-3 mr-1" />}
                          {backup.status === 'failed' && <XCircle className="w-3 h-3 mr-1" />}
                          {backup.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-xs">{new Date(backup.createdAt).toLocaleString()}</TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => downloadBackup(backup)} title="Download">
                            <Download className="w-3.5 h-3.5" />
                          </Button>
                          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => restoreFromBackup(backup)} title="Restore">
                            <Upload className="w-3.5 h-3.5" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Restore Dialog */}
      <Dialog open={restoreOpen} onOpenChange={setRestoreOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Restore from Backup</DialogTitle>
            <DialogDescription>
              Are you sure you want to restore from this backup? This will overwrite current data.
            </DialogDescription>
          </DialogHeader>
          {selectedBackup && (
            <div className="py-2 text-sm space-y-1">
              <p><span className="text-muted-foreground">File:</span> {selectedBackup.filename}</p>
              <p><span className="text-muted-foreground">Size:</span> {formatSize(selectedBackup.size)}</p>
              <p><span className="text-muted-foreground">Date:</span> {new Date(selectedBackup.createdAt).toLocaleString()}</p>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setRestoreOpen(false)}>{t.actions.cancel}</Button>
            <Button onClick={confirmRestore} variant="destructive">
              {t.backup.restoreBackup}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
