'use client';

import { useEffect, useMemo, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { handleBackupAndWipeDatabases, handleCreateDatabaseBackup, handleRestoreDatabases } from '@/lib/actions';
import { useToast } from '@/hooks/use-toast';
import { getFriendlyFileName } from '@/lib/file-name-translations';
import { AlertTriangle, Database, Download, Loader2, RotateCcw, ShieldAlert, Trash2 } from 'lucide-react';

type BackupSettingsPanelProps = {
  dbFiles: string[];
  backupIds: string[];
};

export default function BackupSettingsPanel({ dbFiles, backupIds }: BackupSettingsPanelProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [isBackupDialogOpen, setIsBackupDialogOpen] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<string[]>(dbFiles);
  const [selectedBackupId, setSelectedBackupId] = useState('');
  const [wipePassword, setWipePassword] = useState('');
  const [restorePassword, setRestorePassword] = useState('');
  const [isBackingUp, startBackupTransition] = useTransition();
  const [isRestoring, startRestoreTransition] = useTransition();
  const availableBackupIds = useMemo(() => [...backupIds].sort((left, right) => right.localeCompare(left)), [backupIds]);

  const closeBackupDialog = () => {
    const activeElement = document.activeElement;
    if (activeElement instanceof HTMLElement) {
      activeElement.blur();
    }
    setIsBackupDialogOpen(false);
  };

  useEffect(() => {
    setSelectedFiles((current) => {
      const filtered = current.filter((file) => dbFiles.includes(file));
      return filtered.length > 0 ? filtered : dbFiles;
    });
  }, [dbFiles]);

  useEffect(() => {
    if (!selectedBackupId || !availableBackupIds.includes(selectedBackupId)) {
      setSelectedBackupId(availableBackupIds[0] ?? '');
    }
  }, [availableBackupIds, selectedBackupId]);

  const toggleFile = (file: string, checked: boolean) => {
    setSelectedFiles((current) => {
      if (checked) {
        return current.includes(file) ? current : [...current, file];
      }
      return current.filter((entry) => entry !== file);
    });
  };

  const selectAllFiles = () => setSelectedFiles(dbFiles);
  const clearFiles = () => setSelectedFiles([]);

  const ensureFilesSelected = (): boolean => {
    if (selectedFiles.length === 0) {
      toast({ title: 'تنبيه', description: 'اختر ملفًا واحدًا على الأقل قبل إنشاء النسخة الاحتياطية.', variant: 'destructive' });
      return false;
    }
    return true;
  };

  const runBackupOnly = () => {
    if (!ensureFilesSelected()) {
      return;
    }

    startBackupTransition(async () => {
      const result = await handleCreateDatabaseBackup({ files: selectedFiles });
      if (result.success) {
        toast({ title: 'تم إنشاء النسخة الاحتياطية', description: result.backupId ? `تم حفظ النسخة داخل ${result.backupId}` : 'تم حفظ النسخة بنجاح.' });
        router.refresh();
        return;
      }

      toast({
        title: 'فشل إنشاء النسخة الاحتياطية',
        description: result.error ?? 'تعذر تنفيذ العملية.',
        variant: 'destructive',
      });
    });
  };

  const openWipeDialog = () => {
    if (!ensureFilesSelected()) {
      return;
    }
    setIsBackupDialogOpen(true);
  };

  const runBackupAndWipe = () => {
    if (!ensureFilesSelected()) {
      return;
    }
    if (!wipePassword.trim()) {
      toast({ title: 'تنبيه', description: 'أدخل كلمة مرورك لتأكيد عملية الإفراغ.', variant: 'destructive' });
      return;
    }

    startBackupTransition(async () => {
      const result = await handleBackupAndWipeDatabases({ files: selectedFiles, password: wipePassword.trim() });
      if (result.success) {
        toast({ title: 'تم حفظ نسخة قبل الإفراغ', description: result.backupId ? `النسخة محفوظة داخل ${result.backupId}` : 'تم الحفظ ثم الإفراغ بنجاح.' });
        setWipePassword('');
        closeBackupDialog();
        router.refresh();
        return;
      }

      toast({
        title: 'فشل النسخ والإفراغ',
        description: result.error ?? 'تعذر تنفيذ العملية.',
        variant: 'destructive',
      });
    });
  };

  const runRestore = () => {
    if (!selectedBackupId) {
      toast({ title: 'تنبيه', description: 'اختر نسخة احتياطية للاستعادة.', variant: 'destructive' });
      return;
    }
    if (!restorePassword.trim()) {
      toast({ title: 'تنبيه', description: 'أدخل كلمة المرور لتأكيد الاستعادة.', variant: 'destructive' });
      return;
    }

    startRestoreTransition(async () => {
      const result = await handleRestoreDatabases({
        backupId: selectedBackupId,
        files: selectedFiles.length > 0 ? selectedFiles : undefined,
        password: restorePassword.trim(),
      });

      if (result.success) {
        toast({ title: 'تمت الاستعادة', description: 'تمت استعادة الملفات المحددة من النسخة المختارة.' });
        setRestorePassword('');
        router.refresh();
        return;
      }

      toast({
        title: 'فشل الاستعادة',
        description: result.error ?? 'تعذر تنفيذ العملية.',
        variant: 'destructive',
      });
    });
  };

  const selectedFilesSummary = selectedFiles.length > 0 ? selectedFiles.map((f) => getFriendlyFileName(f)).join('، ') : 'لم يتم اختيار ملفات';

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Database className="h-5 w-5" />
          النسخ الاحتياطي والاستعادة
        </CardTitle>
        <CardDescription>
          اختر ملفات قاعدة البيانات، أنشئ نسخة احتياطية، ثم استعدها لاحقًا عند الحاجة.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {dbFiles.length === 0 ? (
          <Alert>
            <AlertTriangle className="h-4 w-4" />
            <AlertTitle>لا توجد ملفات قاعدة بيانات قابلة للنسخ</AlertTitle>
            <AlertDescription>تعذر العثور على جداول محلية قابلة للنسخ الاحتياطي في الوقت الحالي.</AlertDescription>
          </Alert>
        ) : (
          <>
            <Alert variant="destructive">
              <ShieldAlert className="h-4 w-4" />
              <AlertTitle>تنبيه مهم</AlertTitle>
              <AlertDescription>
                النسخ الاحتياطي الحالي يستخدم الإجراء الموجود مسبقًا، وهو يحفظ نسخة من الملفات المحددة ثم يفرغها من قاعدة البيانات المحلية.
                استخدمه فقط بعد التأكد من الملفات المطلوبة.
              </AlertDescription>
            </Alert>

            <div className="space-y-3 rounded-lg border p-4">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <div>
                  <h3 className="text-sm font-semibold">الملفات المحددة</h3>
                  <p className="text-xs text-muted-foreground">{selectedFiles.length} من {dbFiles.length} ملف</p>
                </div>
                <div className="flex flex-wrap gap-2">
                  <Button type="button" variant="outline" size="sm" onClick={selectAllFiles}>
                    تحديد الكل
                  </Button>
                  <Button type="button" variant="outline" size="sm" onClick={clearFiles}>
                    إلغاء التحديد
                  </Button>
                </div>
              </div>

              <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
                {dbFiles.map((file) => (
                  <label key={file} className="flex items-center gap-3 rounded-md border px-3 py-2 text-sm">
                    <Checkbox checked={selectedFiles.includes(file)} onCheckedChange={(checked) => toggleFile(file, checked === true)} />
                    <span className="break-all" title={file}>{getFriendlyFileName(file)}</span>
                  </label>
                ))}
              </div>
            </div>

            <div className="grid gap-6 lg:grid-cols-2">
              <div className="space-y-4 rounded-lg border p-4">
                <div className="flex items-center gap-2">
                  <Download className="h-4 w-4" />
                  <h3 className="font-semibold">إنشاء نسخة احتياطية</h3>
                </div>
                <p className="text-sm text-muted-foreground">
                  سيتم حفظ نسخة من الملفات المحددة في مجلد النسخ الاحتياطية بدون حذف أي بيانات من قاعدة البيانات.
                </p>
                <Button type="button" onClick={runBackupOnly} disabled={isBackingUp} className="w-full">
                  {isBackingUp ? (
                    <span className="flex items-center gap-2"><Loader2 className="h-4 w-4 animate-spin" /> جارٍ التحضير...</span>
                  ) : (
                    'إنشاء نسخة احتياطية فقط'
                  )}
                </Button>
              </div>

              <div className="space-y-4 rounded-lg border p-4">
                <div className="flex items-center gap-2">
                  <Trash2 className="h-4 w-4" />
                  <h3 className="font-semibold">نسخ احتياطي ثم إفراغ</h3>
                </div>
                <p className="text-sm text-muted-foreground">
                  سيتم حفظ نسخة احتياطية أولًا ثم تفريغ الملفات المحددة من قاعدة البيانات المحلية.
                </p>
                <div className="space-y-2">
                  <Label htmlFor="wipe-password">كلمة المرور للتأكيد</Label>
                  <Input
                    id="wipe-password"
                    type="password"
                    value={wipePassword}
                    onChange={(event) => setWipePassword(event.target.value)}
                    placeholder="أدخل كلمة المرور"
                  />
                </div>
                <Button type="button" variant="destructive" onClick={openWipeDialog} disabled={isBackingUp}>
                  {isBackingUp ? (
                    <span className="flex items-center gap-2"><Loader2 className="h-4 w-4 animate-spin" /> جارٍ التحضير...</span>
                  ) : (
                    'النسخ ثم الإفراغ'
                  )}
                </Button>
              </div>

              <div className="space-y-4 rounded-lg border p-4 lg:col-span-2">
                <div className="flex items-center gap-2">
                  <RotateCcw className="h-4 w-4" />
                  <h3 className="font-semibold">استعادة نسخة سابقة</h3>
                </div>
                <p className="text-sm text-muted-foreground">
                  اختر نسخة احتياطية ثم استعد الملفات المحددة. إذا تركت الملفات محددة فسيتم استعادة الجميع.
                </p>
                <div className="space-y-2">
                  <Label>النسخة الاحتياطية</Label>
                  {availableBackupIds.length > 0 ? (
                    <Select value={selectedBackupId} onValueChange={setSelectedBackupId}>
                      <SelectTrigger>
                        <SelectValue placeholder="اختر نسخة احتياطية" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableBackupIds.map((backupId) => (
                          <SelectItem key={backupId} value={backupId}>
                            {backupId}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  ) : (
                    <div className="rounded-md border px-3 py-2 text-sm text-muted-foreground">
                      لا توجد نسخ محفوظة بعد.
                    </div>
                  )}
                </div>
                <Button type="button" onClick={runRestore} disabled={isRestoring || availableBackupIds.length === 0}>
                  {isRestoring ? (
                    <span className="flex items-center gap-2"><Loader2 className="h-4 w-4 animate-spin" /> جارٍ الاستعادة...</span>
                  ) : (
                    'استعادة النسخة المحددة'
                  )}
                </Button>
              </div>
            </div>

            <div className="rounded-md bg-muted/40 p-3 text-sm text-muted-foreground">
              الملفات المحددة حاليًا: {selectedFilesSummary}
            </div>
          </>
        )}
      </CardContent>

      <Dialog open={isBackupDialogOpen} onOpenChange={(open) => {
        if (!open) {
          closeBackupDialog();
          return;
        }
        setIsBackupDialogOpen(true);
      }}>
        <DialogContent className="sm:max-w-xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-destructive" />
              تأكيد إنشاء النسخة الاحتياطية
            </DialogTitle>
            <DialogDescription>
              سيتم إنشاء نسخة احتياطية من الملفات التالية ثم تفريغها من قاعدة البيانات المحلية:
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 text-sm">
            <div className="rounded-md border bg-muted/30 p-3">
              {selectedFiles.length > 0 ? selectedFiles.map((f) => getFriendlyFileName(f)).join('، ') : 'لا توجد ملفات محددة'}
            </div>
            <div className="space-y-2">
              <Label htmlFor="backup-confirm-password">كلمة المرور</Label>
              <Input
                id="backup-confirm-password"
                type="password"
                value={wipePassword}
                onChange={(event) => setWipePassword(event.target.value)}
                placeholder="أدخل كلمة المرور للتأكيد"
              />
            </div>
          </div>

          <DialogFooter>
            <DialogClose asChild>
              <Button type="button" variant="outline" disabled={isBackingUp}>
                إلغاء
              </Button>
            </DialogClose>
            <Button type="button" variant="destructive" onClick={runBackupAndWipe} disabled={isBackingUp}>
              {isBackingUp ? (
                <span className="flex items-center gap-2"><Loader2 className="h-4 w-4 animate-spin" /> جارٍ التنفيذ...</span>
              ) : (
                'تأكيد النسخ ثم الإفراغ'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}