import { useEffect, useState } from 'react';
import { Construction, Eye, Save, AlertTriangle, Power, PowerOff } from 'lucide-react';
import { Card, CardBody, CardHeader, CardTitle, CardDescription } from './ui/Card';
import { Button } from './ui/Button';
import { Field, Input, Switch } from './ui/Input';
import { DateTimePicker } from './ui/DateTimePicker';
import { Loading, ErrorState, Toast } from './ui/States';
import { useConfirm } from './ConfirmProvider';
import { api, type MaintenanceState } from '@/lib/api';
import { formatDateTime } from '@/lib/format';
import { useQuery, useMutation } from '@/hooks/useQuery';

/**
 * The auto-during-restore toggle (which previously lived inside the Settings
 * page's Performance card) is controlled by the parent so it can be saved as
 * part of the same settings POST that handles the other Settings page
 * fields. Optional — if a caller mounts MaintenanceCard standalone (no
 * Settings parent), the toggle row hides cleanly.
 */
interface Props {
  autoDuringRestore?: boolean;
  onAutoDuringRestoreChange?: (next: boolean) => void;
}

export function MaintenanceCard({ autoDuringRestore, onAutoDuringRestoreChange }: Props = {}) {
  const { data, isLoading, error, refetch } = useQuery(() => api.maintenance.get(), []);
  const [form, setForm] = useState<MaintenanceState | null>(null);
  const [toast, setToast] = useState<{ msg: string; tone: 'success' | 'danger' } | null>(null);
  const confirm = useConfirm();
  const showAutoToggle = autoDuringRestore !== undefined && onAutoDuringRestoreChange !== undefined;

  useEffect(() => { if (data) setForm(data); }, [data]);

  const save = useMutation(
    (next: Partial<MaintenanceState>) => api.maintenance.update(next),
    { onSuccess: () => { refetch(); setToast({ msg: 'Saved', tone: 'success' }); },
      onError:   (e) => setToast({ msg: e.message, tone: 'danger' }) },
  );

  if (isLoading || !form) return <Loading label="Loading maintenance mode…" />;
  if (error)              return <ErrorState error={error} onRetry={refetch} />;

  const toggleActive = async () => {
    if (!form.active) {
      const ok = await confirm({
        title: 'Enable maintenance mode now?',
        description: 'Visitors will see your branded "be right back" page instead of the site. You and other admins keep full access.',
        confirmLabel: 'Enable',
        tone: 'danger',
      });
      if (!ok) return;
    }
    const next = !form.active;
    save.mutate({ ...form, active: next });
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-3 flex-1">
          <span className={
            'h-8 w-8 grid place-items-center rounded-lg ' +
            (form.active ? 'bg-amber-100 text-amber-700' : 'bg-ink-100 text-ink-700')
          }>
            <Construction className="h-4 w-4" />
          </span>
          <div>
            <CardTitle>Maintenance mode</CardTitle>
            <CardDescription>
              Show a branded "be right back" page to visitors while you do work on the site.
            </CardDescription>
          </div>
        </div>
        <span className={
          'inline-flex items-center gap-1.5 px-2 py-1 text-[11px] font-medium rounded-md ring-1 ring-inset ' +
          (form.active ? 'bg-amber-50 text-amber-800 ring-amber-200' : 'bg-emerald-50 text-emerald-700 ring-emerald-200')
        }>
          <span className={'h-1.5 w-1.5 rounded-full ' + (form.active ? 'bg-amber-500' : 'bg-emerald-500')} />
          {form.active ? 'ACTIVE' : 'OFF'}
        </span>
      </CardHeader>

      <CardBody className="space-y-4">
        {/* Big toggle row */}
        <div className={
          'flex items-center justify-between p-4 rounded-xl border-2 ' +
          (form.active ? 'border-amber-300 bg-amber-50/50' : 'border-ink-200 bg-ink-50/40')
        }>
          <div className="flex items-start gap-3">
            {form.active
              ? <AlertTriangle className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
              : <Power className="h-5 w-5 text-ink-500 shrink-0 mt-0.5" />}
            <div>
              <p className="text-sm font-semibold text-ink-900">
                {form.active ? 'Visitors are seeing the maintenance page' : 'Site is fully open to visitors'}
              </p>
              {form.active && form.started_at && (
                <p className="text-xs text-ink-600 mt-0.5">
                  Started {formatDateTime(form.started_at + ' UTC')}{form.started_by ? ` by ${form.started_by}` : ''}
                </p>
              )}
              {!form.active && (
                <p className="text-xs text-ink-500 mt-0.5">Toggle to send all non-admin traffic to a branded 503 page.</p>
              )}
            </div>
          </div>
          <Button
            variant={form.active ? 'danger' : 'primary'}
            leftIcon={form.active ? <PowerOff className="h-4 w-4" /> : <Power className="h-4 w-4" />}
            onClick={toggleActive}
            disabled={save.isLoading}
          >
            {form.active ? 'Turn off' : 'Enable'}
          </Button>
        </div>

        {/* Auto-during-restore — moved here from the Performance card so all
            maintenance-mode concepts live together. Stays controlled by the
            parent Settings page so the value saves alongside the other
            Settings form fields on one button press. Hidden when the
            component is mounted standalone (props undefined). */}
        {showAutoToggle && (
          <label className="flex items-start gap-3 p-3 rounded-lg border border-ink-200 bg-white cursor-pointer">
            <Switch
              checked={!!autoDuringRestore}
              onChange={(v) => onAutoDuringRestoreChange!(v)}
            />
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-ink-900">Auto-enable during restore</p>
              <p className="text-xs text-ink-500 mt-0.5">
                Show this page to visitors automatically while a backup is being restored,
                then turn it back off when the restore finishes.
              </p>
            </div>
          </label>
        )}

        {/* Customisation form */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <Field label="Heading" hint="Shown large on the page">
            <Input value={form.heading} onChange={(e) => setForm({ ...form, heading: e.target.value })} />
          </Field>
          <Field label="ETA (optional)" hint="When the site comes back online">
            <DateTimePicker
              value={form.eta ? form.eta.slice(0, 16) : ''}
              onChange={(next) => setForm({ ...form, eta: next })}
              placeholder="Pick a date and time"
            />
          </Field>
        </div>
        <Field label="Message" hint="One or two friendly sentences for visitors">
          <textarea
            value={form.message}
            onChange={(e) => setForm({ ...form, message: e.target.value })}
            className="w-full min-h-[80px] rounded-lg border border-ink-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 focus:border-brand-500"
          />
        </Field>
        <Field label="Bypass IPs" hint="One IP per line. These visitors see the live site even when maintenance mode is on.">
          <textarea
            value={(form.bypass_ips ?? []).join('\n')}
            onChange={(e) => setForm({ ...form, bypass_ips: e.target.value.split('\n').map((s) => s.trim()).filter(Boolean) })}
            placeholder={'203.0.113.42\n198.51.100.7'}
            className="w-full min-h-[60px] rounded-lg border border-ink-200 bg-white px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 focus:border-brand-500"
          />
        </Field>

        <div className="flex items-center gap-2 pt-2 border-t border-ink-100">
          <Button variant="primary" leftIcon={<Save className="h-4 w-4" />}
            disabled={save.isLoading}
            onClick={() => save.mutate(form)}>
            Save changes
          </Button>
          <a
            href={window.Backreload?.siteUrl ?? '/'}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 h-9 px-3 text-sm font-medium rounded-lg text-ink-700 hover:bg-ink-100 ml-auto"
          >
            <Eye className="h-4 w-4" />
            Preview site
          </a>
        </div>

        <p className="text-[11px] text-ink-500">
          Tip: admins (you) always see the live site. Open the preview in a private/incognito window to view the maintenance page yourself.
        </p>
      </CardBody>

      {toast && <Toast message={toast.msg} tone={toast.tone} onClose={() => setToast(null)} />}
    </Card>
  );
}
