'use client';

import { useState, useEffect, useCallback } from 'react';
import { AlertTriangle, Power } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { createProxyFetch } from '@/lib/proxy-fetch';

interface MaintenanceStatus {
  mode: string;
  message?: string;
  bypassRoles?: string[];
  bypassIPs?: string[];
  scheduledAt?: string;
  endsAt?: string;
}

const modeConfig: Record<string, { label: string; color: string; description: string }> = {
  off: {
    label: 'Normal',
    color: 'bg-emerald-50 text-emerald-700',
    description: 'All services operational',
  },
  read_only: {
    label: 'Read Only',
    color: 'bg-amber-50 text-amber-700',
    description: 'Write operations disabled',
  },
  maintenance: {
    label: 'Maintenance',
    color: 'bg-orange-50 text-orange-700',
    description: 'Platform under maintenance',
  },
  emergency: {
    label: 'Emergency',
    color: 'bg-red-50 text-red-700',
    description: 'Emergency lockdown active',
  },
};

const apiFetch = createProxyFetch('/api/maintenance');

export default function MaintenancePage() {
  const [status, setStatus] = useState<MaintenanceStatus>({ mode: 'off' });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [newMode, setNewMode] = useState('off');
  const [newMessage, setNewMessage] = useState('');

  const loadData = useCallback(async () => {
    setLoading(true);
    const data = await apiFetch('full');
    if (data?.mode) {
      setStatus(data);
      setNewMode(data.mode);
      setNewMessage(data.message || '');
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  async function handleSave() {
    setSaving(true);
    await apiFetch('', {
      method: 'PUT',
      body: JSON.stringify({ mode: newMode, message: newMessage || undefined }),
    });
    setSaving(false);
    loadData();
  }

  const cfg = modeConfig[status.mode] || modeConfig.off;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Maintenance Mode</h1>
        <p className="text-sm text-muted-foreground">
          Control platform availability: normal, read-only, maintenance, or emergency
        </p>
      </div>

      {loading ? (
        <div className="text-center text-muted-foreground py-8">Loading...</div>
      ) : (
        <>
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <Power className="h-4 w-4" /> Current Status
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-4">
                <Badge className={`${cfg.color} border-0 text-sm px-3 py-1`}>{cfg.label}</Badge>
                <span className="text-sm text-muted-foreground">{cfg.description}</span>
              </div>
              {status.message && (
                <div className="mt-3 p-3 bg-muted rounded-lg">
                  <p className="text-sm">{status.message}</p>
                </div>
              )}
              {status.mode !== 'off' && status.bypassRoles && status.bypassRoles.length > 0 && (
                <div className="mt-3 text-xs text-muted-foreground">
                  Bypass roles: {status.bypassRoles.join(', ')}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">Change Mode</CardTitle>
              <CardDescription>
                Switch between maintenance modes. Admin roles always bypass.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label>Mode</Label>
                <Select value={newMode} onValueChange={setNewMode}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="off">Normal (all services active)</SelectItem>
                    <SelectItem value="read_only">Read Only (writes blocked)</SelectItem>
                    <SelectItem value="maintenance">Maintenance (platform unavailable)</SelectItem>
                    <SelectItem value="emergency">Emergency (full lockdown)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Message (shown to users)</Label>
                <Textarea
                  placeholder="Optional message..."
                  value={newMessage}
                  onChange={e => setNewMessage(e.target.value)}
                  rows={2}
                />
              </div>
              {newMode === 'emergency' && (
                <div className="flex items-center gap-2 text-red-600 text-sm">
                  <AlertTriangle className="h-4 w-4" />
                  Emergency mode blocks ALL requests except admin bypass.
                </div>
              )}
              <Button
                onClick={handleSave}
                disabled={saving}
                variant={newMode === 'emergency' ? 'destructive' : 'default'}
              >
                {saving
                  ? 'Saving...'
                  : newMode === status.mode
                    ? 'Update Message'
                    : `Switch to ${modeConfig[newMode]?.label || newMode}`}
              </Button>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
