import { Button } from '@/components/ui';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card.tsx';
import { Switch } from '@/components/ui/Switch.tsx';
import Textarea from '@/components/ui/Textarea.tsx';
import {
  useMaintenanceSetting,
  useSetMaintenance,
  useSystemHealth,
} from '@/hooks/api/useAdminAPI.ts';
import { useTranslation } from '@/hooks/useI18n.tsx';
import { useToast } from '@/hooks/useToast.ts';
import { useEffect, useState } from 'react';

const STORAGE_KEY = 'admin:maintenance:message';

const AdminSettingsMaintenancePage = () => {
  const { t } = useTranslation();
  const { data: health, isLoading } = useSystemHealth();
  const { success } = useToast();

  const [enabled, setEnabled] = useState(false);
  const [message, setMessage] = useState('');
  const [allowedIPsText, setAllowedIPsText] = useState('');

  const { data: maintenance, isLoading: isMaintenanceLoading } = useMaintenanceSetting();
  const setMaintenance = useSetMaintenance();

  // Hydrate from server
  useEffect(() => {
    if (maintenance) {
      setEnabled(maintenance.enabled);
      setMessage(maintenance.message ?? '');
      setAllowedIPsText((maintenance.allowedIPs || []).join(', '));
    }
  }, [maintenance]);

  const handleToggle = () => {
    setEnabled(!enabled);
    success(
      !enabled ? t('admin.settings.maintenance.enabled') : t('admin.settings.maintenance.disabled')
    );
  };

  const handleSave = async () => {
    const allowedIPs = allowedIPsText
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);
    await setMaintenance.mutateAsync({ enabled, message, allowedIPs });
    success(t('admin.settings.maintenance.saved'));
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">{t('admin.settings.maintenance.title')}</h1>
        <p className="text-muted-foreground">{t('admin.settings.maintenance.subtitle')}</p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{t('admin.settings.systemHealth')}</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <p className="text-muted-foreground">Loading…</p>
          ) : (
            <div className="space-y-2">
              <div>
                Status: <strong>{health?.status ?? 'unknown'}</strong>
              </div>
              <div>DB: {health?.database ?? 'unknown'}</div>
              <div>Cache: {health?.cache ?? 'unknown'}</div>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t('admin.settings.maintenance.controls')}</CardTitle>
        </CardHeader>
        <CardContent>
          {maintenance?.enabled && (
            <div className="mb-4 p-3 bg-yellow-50 border-l-4 border-yellow-400">
              <strong className="block">{t('admin.settings.maintenance.active')}</strong>
              <div className="text-sm">{maintenance.message}</div>
            </div>
          )}
          <div className="space-y-4">
            <div className="flex items-center gap-4">
              <Switch checked={enabled} onCheckedChange={handleToggle} />
              <div>
                {enabled
                  ? t('admin.settings.maintenance.enabled')
                  : t('admin.settings.maintenance.disabled')}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                {t('admin.settings.maintenance.message')}
              </label>
              <Textarea value={message} onChange={(e) => setMessage(e.target.value)} />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">
                {t('admin.settings.maintenance.allowed_ips')}
              </label>
              <Textarea
                value={allowedIPsText}
                onChange={(e) => setAllowedIPsText(e.target.value)}
                placeholder="127.0.0.1, 10.0.0.1"
              />
            </div>

            <div>
              <Button onClick={handleSave}>{t('admin.settings.maintenance.save')}</Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default AdminSettingsMaintenancePage;
