'use client';

import { useEffect, 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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { handleGetStorageConfig, handleUpdateStorageConfig } from '@/lib/actions';
import { useToast } from '@/hooks/use-toast';
import { AlertTriangle, HardDrive, Loader2, Settings } from 'lucide-react';

interface StorageConfig {
  backupPath: string;
  codePath: string;
  documentsPath: string;
  autoBackupEnabled: boolean;
  autoBackupIntervalHours: number;
  lastBackupTime?: string;
}

type StorageConfigPanelProps = {
  initialConfig?: StorageConfig;
};

export default function StorageConfigPanel({ initialConfig }: StorageConfigPanelProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [isSaving, startSaveTransition] = useTransition();
  const [config, setConfig] = useState<StorageConfig | null>(initialConfig || null);
  const [isLoading, setIsLoading] = useState(!initialConfig);
  const [backupPath, setBackupPath] = useState(initialConfig?.backupPath || '');
  const [codePath, setCodePath] = useState(initialConfig?.codePath || '');
  const [documentsPath, setDocumentsPath] = useState(initialConfig?.documentsPath || '');
  const [autoBackupEnabled, setAutoBackupEnabled] = useState(initialConfig?.autoBackupEnabled || false);
  const [autoBackupIntervalHours, setAutoBackupIntervalHours] = useState(
    initialConfig?.autoBackupIntervalHours || 3
  );

  // Load config if not provided initially
  useEffect(() => {
    if (!initialConfig) {
      const loadConfig = async () => {
        setIsLoading(true);
        const result = await handleGetStorageConfig();
        if (result.success && result.config) {
          setConfig(result.config);
          setBackupPath(result.config.backupPath);
          setCodePath(result.config.codePath);
          setDocumentsPath(result.config.documentsPath);
          setAutoBackupEnabled(result.config.autoBackupEnabled);
          setAutoBackupIntervalHours(result.config.autoBackupIntervalHours);
        } else {
          toast({
            title: 'تنبيه',
            description: result.error || 'فشل تحميل إعدادات التخزين.',
            variant: 'destructive',
          });
        }
        setIsLoading(false);
      };
      loadConfig();
    }
  }, [initialConfig, toast]);

  const hasChanges = config && (
    backupPath !== config.backupPath ||
    codePath !== config.codePath ||
    documentsPath !== config.documentsPath ||
    autoBackupEnabled !== config.autoBackupEnabled ||
    autoBackupIntervalHours !== config.autoBackupIntervalHours
  );

  const handleSave = () => {
    if (!backupPath || !codePath || !documentsPath) {
      toast({
        title: 'تنبيه',
        description: 'يجب ملء جميع حقول المسارات.',
        variant: 'destructive',
      });
      return;
    }

    startSaveTransition(async () => {
      const result = await handleUpdateStorageConfig({
        backupPath,
        codePath,
        documentsPath,
        autoBackupEnabled,
        autoBackupIntervalHours,
      });

      if (result.success && result.config) {
        setConfig(result.config);
        toast({
          title: 'تم الحفظ',
          description: 'تم حفظ إعدادات التخزين بنجاح.',
        });
        router.refresh();
      } else {
        toast({
          title: 'فشل الحفظ',
          description: result.error || 'تعذر حفظ الإعدادات.',
          variant: 'destructive',
        });
      }
    });
  };

  const handleManualBackup = async () => {
    startSaveTransition(async () => {
      try {
        const response = await fetch('/api/admin/backup', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
        });
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
          throw new Error(errorData.error || `HTTP ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
          const backupPathNote = result.backupPath
            ? `\nالمسار: ${result.backupPath}`
            : '';
          toast({
            title: 'تم بنجاح',
            description: `تم إنشاء نسخة احتياطية: ${result.backupId || '-'}${backupPathNote}`,
          });
          router.refresh();
        } else {
          throw new Error(result.error || 'فشل إنشاء النسخة الاحتياطية');
        }
      } catch (error: any) {
        toast({
          title: 'خطأ',
          description: error?.message || 'حدث خطأ أثناء إنشاء النسخة الاحتياطية.',
          variant: 'destructive',
        });
      }
    });
  };

  const handleReset = () => {
    if (config) {
      setBackupPath(config.backupPath);
      setCodePath(config.codePath);
      setDocumentsPath(config.documentsPath);
      setAutoBackupEnabled(config.autoBackupEnabled);
      setAutoBackupIntervalHours(config.autoBackupIntervalHours);
    }
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <HardDrive className="h-5 w-5" />
            إعدادات التخزين
          </CardTitle>
        </CardHeader>
        <CardContent className="flex items-center justify-center py-8">
          <Loader2 className="h-6 w-6 animate-spin" />
        </CardContent>
      </Card>
    );
  }

  if (!config) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <HardDrive className="h-5 w-5" />
            إعدادات التخزين
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Alert variant="destructive">
            <AlertTriangle className="h-4 w-4" />
            <AlertTitle>خطأ في التحميل</AlertTitle>
            <AlertDescription>تعذر تحميل إعدادات التخزين.</AlertDescription>
          </Alert>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <HardDrive className="h-5 w-5" />
          إعدادات التخزين
        </CardTitle>
        <CardDescription>
          حدد مسارات منفصلة للنسخ الاحتياطية والأكواد والملفات الوثائقية لضمان كفاءة النظام على المدى الطويل.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        <Alert>
          <Settings className="h-4 w-4" />
          <AlertTitle>ملاحظة هامة</AlertTitle>
          <AlertDescription>
            يجب أن تكون المسارات مختلفة وغير متداخلة. لا يمكن تغيير المسارات بينما يجري النسخ الاحتياطي.
          </AlertDescription>
        </Alert>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="backup-path">مسار النسخ الاحتياطية</Label>
            <Input
              id="backup-path"
              type="text"
              value={backupPath}
              onChange={(e) => setBackupPath(e.target.value)}
              placeholder="مثال: C:\\data\\backups"
              disabled={isSaving}
            />
            <p className="text-xs text-muted-foreground">
              المسار الحالي: {config.backupPath}
            </p>
            <p className="text-xs text-muted-foreground">
              ملاحظة: يجب أن يكون المسار مختلفًا عن مسارات الأكواد والملفات
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="code-path">مسار الأكواد</Label>
            <Input
              id="code-path"
              type="text"
              value={codePath}
              onChange={(e) => setCodePath(e.target.value)}
              placeholder="مثال: C:\\app"
              disabled={isSaving}
            />
            <p className="text-xs text-muted-foreground">
              المسار الحالي: {config.codePath}
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="documents-path">مسار الملفات الوثائقية</Label>
            <Input
              id="documents-path"
              type="text"
              value={documentsPath}
              onChange={(e) => setDocumentsPath(e.target.value)}
              placeholder="مثال: C:\\data\\uploads"
              disabled={isSaving}
            />
            <p className="text-xs text-muted-foreground">
              المسار الحالي: {config.documentsPath}
            </p>
          </div>
        </div>

        <div className="space-y-4 rounded-lg border p-4">
          <div className="flex items-center gap-3">
            <Checkbox
              id="auto-backup"
              checked={autoBackupEnabled}
              onCheckedChange={(checked) => setAutoBackupEnabled(checked === true)}
              disabled={isSaving}
            />
            <Label htmlFor="auto-backup" className="cursor-pointer">
              تفعيل النسخ الاحتياطي التلقائي
            </Label>
          </div>

          {autoBackupEnabled && (
            <div className="space-y-2 pl-8">
              <Label htmlFor="backup-interval">فترة النسخ الاحتياطي (ساعات)</Label>
              <Input
                id="backup-interval"
                type="number"
                min="1"
                max="24"
                value={autoBackupIntervalHours}
                onChange={(e) => setAutoBackupIntervalHours(Number(e.target.value))}
                disabled={isSaving}
              />
              <p className="text-xs text-muted-foreground">
                سيتم إنشاء نسخة احتياطية تلقائية كل {autoBackupIntervalHours} ساعة.
              </p>
            </div>
          )}

          {config.lastBackupTime && (
            <div className="text-xs text-muted-foreground">
              آخر نسخة احتياطية: {new Date(config.lastBackupTime).toLocaleString('ar-SA')}
            </div>
          )}
        </div>

        <div className="flex gap-2">
          <Button
            onClick={handleSave}
            disabled={isSaving || !hasChanges}
          >
            {isSaving ? (
              <span className="flex items-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                جاري الحفظ...
              </span>
            ) : (
              'حفظ التغييرات'
            )}
          </Button>

          <Button
            variant="outline"
            onClick={handleManualBackup}
            disabled={isSaving}
          >
            {isSaving ? (
              <span className="flex items-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                جاري النسخ...
              </span>
            ) : (
              'إنشاء نسخة احتياطية الآن'
            )}
          </Button>

          {hasChanges && (
            <Button
              variant="outline"
              onClick={handleReset}
              disabled={isSaving}
            >
              إلغاء
            </Button>
          )}
        </div>
      </CardContent>
    </Card>
  );
}
