'use client';

import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/Button';
import {
  getMobileDeStatus,
  pushToMobileDe,
  type MobileDeStatusResponse,
} from '@/lib/vehicles';

interface MobileDeStatusProps {
  vehicleId: string;
}

const STATUS_STYLES: Record<string, string> = {
  synced: 'bg-green-100 text-green-800',
  pending: 'bg-yellow-100 text-yellow-800',
  fehler: 'bg-red-100 text-red-800',
  deleted: 'bg-gray-100 text-gray-800',
};

const STATUS_LABELS: Record<string, string> = {
  synced: 'Synced',
  pending: 'Pending',
  fehler: 'Error',
  deleted: 'Deleted',
};

export function MobileDeStatus({ vehicleId }: MobileDeStatusProps) {
  const [status, setStatus] = useState<MobileDeStatusResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [pushing, setPushing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchStatus = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getMobileDeStatus(vehicleId);
      setStatus(data);
    } catch (err: unknown) {
      const apiErr = err as { error?: { message?: string } };
      setError(apiErr?.error?.message || 'Failed to load mobile.de status');
    } finally {
      setLoading(false);
    }
  }, [vehicleId]);

  useEffect(() => {
    fetchStatus();
  }, [fetchStatus]);

  const handlePush = async () => {
    setPushing(true);
    setError(null);
    try {
      await pushToMobileDe(vehicleId);
      await fetchStatus();
    } catch (err: unknown) {
      const apiErr = err as { error?: { message?: string } };
      setError(apiErr?.error?.message || 'Failed to push to mobile.de');
    } finally {
      setPushing(false);
    }
  };

  const syncStatus = status?.sync_status || 'pending';
  const statusStyle = STATUS_STYLES[syncStatus] || 'bg-gray-100 text-gray-800';
  const statusLabel = STATUS_LABELS[syncStatus] || syncStatus;

  return (
    <div data-testid="mobile-de-status" className="p-6 bg-surface rounded-lg border border-border space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold text-text">mobile.de Status</h2>
        <Button
          variant="primary"
          loading={pushing}
          onClick={handlePush}
          data-testid="mobile-de-push-button"
        >
          Push to mobile.de
        </Button>
      </div>

      {loading ? (
        <div data-testid="mobile-de-loading" className="text-text-muted">
          Loading status...
        </div>
      ) : error ? (
        <div data-testid="mobile-de-error" className="text-error">
          {error}
        </div>
      ) : status ? (
        <div className="space-y-3">
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium text-text-muted">Sync Status:</span>
            <span
              data-testid="mobile-de-sync-status"
              className={`px-3 py-1 rounded-full text-sm font-medium ${statusStyle}`}
            >
              {statusLabel}
            </span>
          </div>

          <div data-testid="mobile-de-synced" className="grid grid-cols-2 gap-4">
            <div>
              <dt className="text-sm font-medium text-text-muted">Synced</dt>
              <dd className="text-text">{status.synced ? 'Yes' : 'No'}</dd>
            </div>
            <div>
              <dt className="text-sm font-medium text-text-muted">Ad ID</dt>
              <dd className="text-text">{status.ad_id || '—'}</dd>
            </div>
            <div>
              <dt className="text-sm font-medium text-text-muted">Synced At</dt>
              <dd className="text-text">
                {status.synced_at ? new Date(status.synced_at).toLocaleString('de-DE') : '—'}
              </dd>
            </div>
          </div>

          {status.error_log && (
            <div data-testid="mobile-de-error-log" className="p-3 bg-error/10 text-error rounded-lg text-sm">
              <strong>Error:</strong> {status.error_log}
            </div>
          )}
        </div>
      ) : null}
    </div>
  );
}
