import { Component, JSX, onMount, createSignal } from 'solid-js';
import { ComponentProps } from 'solid-js';

interface StatCardProps {
  title: string;
  value: string | number;
  icon: JSX.Element;
  color?: string;
}

const StatCard: Component<StatCardProps> = (props) => {
  return (
    <div class="dashboard-stat-card">
      <div class="dashboard-stat-icon" style={{ background: props.color || 'rgba(59, 130, 246, 0.1)', color: props.color || 'var(--accent-primary)' }}>
        {props.icon}
      </div>
      <div class="dashboard-stat-info">
        <div class="dashboard-stat-value">{props.value}</div>
        <div class="dashboard-stat-label">{props.title}</div>
      </div>
    </div>
  );
};

interface PropertyCardProps {
  id: string;
  address: string;
  status: 'monitored' | 'alert' | 'error';
  lastChange: string | null;
  alertCount: number;
  onRemove: (id: string) => void;
}

const PropertyCard: Component<PropertyCardProps> = (props) => {
  const statusBadge = () => {
    switch (props.status) {
      case 'alert':
        return <span class="badge badge-alert">Alert</span>;
      case 'error':
        return <span class="badge badge-error">Error</span>;
      default:
        return <span class="badge badge-ok">Monitored</span>;
    }
  };

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return 'Never';
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  return (
    <div class="property-card">
      <div class="property-card-header">
        <div class="property-address">{props.address}</div>
        {statusBadge()}
      </div>
      <div class="property-card-body">
        <div class="property-meta">
          <span>Changes: {props.alertCount}</span>
          <span>Last change: {formatDate(props.lastChange)}</span>
        </div>
      </div>
      <div class="property-card-footer">
        <button class="btn-icon" onclick={() => props.onRemove(props.id)} title="Remove property">
          &times;
        </button>
      </div>
    </div>
  );
};

interface AlertItem {
  id: string;
  propertyAddress: string;
  severity: string;
  title: string;
  message: string;
  isRead: boolean;
  createdAt: string;
}

interface AlertsListProps {
  alerts: AlertItem[];
  onMarkRead: (id: string) => void;
}

const AlertsList: Component<AlertsListProps> = (props) => {
  const severityColor = (severity: string) => {
    switch (severity) {
      case 'CRITICAL':
        return 'var(--error)';
      case 'HIGH':
        return '#f97316';
      case 'MEDIUM':
        return '#eab308';
      default:
        return 'var(--accent-primary)';
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  if (props.alerts.length === 0) {
    return (
      <div class="empty-state">
        <h2>No alerts</h2>
        <p>All monitored properties are secure.</p>
      </div>
    );
  }

  return (
    <div class="alerts-list">
      {props.alerts.map((alert) => (
        <div class={`alert-item ${alert.isRead ? 'alert-read' : 'alert-unread'}`}>
          <div class="alert-severity" style={{ background: severityColor(alert.severity) }}>
            {alert.severity}
          </div>
          <div class="alert-content">
            <div class="alert-title">{alert.title}</div>
            <div class="alert-property">{alert.propertyAddress}</div>
            <div class="alert-message">{alert.message}</div>
            <div class="alert-time">{formatDate(alert.createdAt)}</div>
          </div>
          {!alert.isRead && (
            <button class="btn-small" onclick={() => props.onMarkRead(alert.id)}>
              Mark read
            </button>
          )}
        </div>
      ))}
    </div>
  );
};

interface AddPropertyFormProps {
  onAdd: (address: string) => Promise<void>;
  canAddMore: boolean;
  limit: number;
  monitoredCount: number;
}

const AddPropertyForm: Component<AddPropertyFormProps> = (props) => {
  const [address, setAddress] = createSignal('');
  const [loading, setLoading] = createSignal(false);
  const [error, setError] = createSignal('');

  const handleSubmit = async (e: SubmitEvent) => {
    e.preventDefault();
    const addr = address().trim();
    if (!addr) {
      setError('Address is required');
      return;
    }
    const addressPattern = /^\d+[\s,].+$/i;
    if (!addressPattern.test(addr)) {
      setError('Please enter a valid street address (e.g., 123 Main Street)');
      return;
    }
    setLoading(true);
    setError('');
    try {
      await props.onAdd(addr);
      setAddress('');
    } catch {
      setError('Failed to add property. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div class="add-property-form">
      <h3>Add a property to monitor</h3>
      <form onSubmit={(e) => handleSubmit(e as unknown as SubmitEvent)}>
        <div class="form-row">
          <input
            type="text"
            placeholder="Enter street address"
            value={address()}
            onInput={(e) => setAddress((e.target as HTMLInputElement).value)}
            disabled={loading() || !props.canAddMore}
          />
          <button type="submit" disabled={loading() || !props.canAddMore}>
            {loading() ? 'Adding...' : 'Add Property'}
          </button>
        </div>
      </form>
      {error() && <div class="form-error">{error()}</div>}
      {!props.canAddMore && (
        <div class="limit-warning">
          Property limit reached ({props.monitoredCount}/{props.limit}). Upgrade to add more.
        </div>
      )}
    </div>
  );
};

const DashboardPage: Component = () => {
  const [stats, setStats] = createSignal<{
    monitoredProperties: number;
    tier: string;
    isPremium: boolean;
    propertyLimit: number;
    canAddMore: boolean;
    recentAlertCount: number;
    criticalAlertCount: number;
  } | null>(null);

  const [properties, setProperties] = createSignal<Array<{
    id: string;
    address: string;
    status: 'monitored' | 'alert' | 'error';
    lastScan: string | null;
    lastChange: string | null;
    alertCount: number;
    addedAt: string;
  }>>([]);

  const [alerts, setAlerts] = createSignal<AlertItem[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [error, setError] = createSignal('');
  const [showAlerts, setShowAlerts] = createSignal(false);

  const fetchStats = async () => {
    try {
      const res = await fetch('/hometitle/properties/stats');
      if (!res.ok) {
        if (res.status === 401) {
          setError('Please log in to view your dashboard');
        } else if (res.status === 404) {
          setError('No active subscription found');
        } else if (res.status === 402) {
          const data = await res.json();
          setError(data.message || 'Premium tier required for home title monitoring');
        }
        return;
      }
      const data = await res.json();
      setStats(data);
    } catch {
      setError('Failed to load dashboard stats');
    }
  };

  const fetchProperties = async () => {
    try {
      const res = await fetch('/hometitle/properties');
      if (!res.ok) return;
      const data = await res.json();
      setProperties(data.properties || []);
    } catch {
      // Silently fail - properties may not be available
    }
  };

  const fetchAlerts = async () => {
    try {
      const res = await fetch('/hometitle/alerts?limit=20');
      if (!res.ok) return;
      const data = await res.json();
      setAlerts(data.alerts || []);
    } catch {
      // Silently fail
    }
  };

  const loadData = async () => {
    setLoading(true);
    await Promise.all([fetchStats(), fetchProperties(), fetchAlerts()]);
    setLoading(false);
  };

  onMount(() => {
    loadData();
  });

  const handleAddProperty = async (address: string) => {
    try {
      const res = await fetch('/hometitle/properties', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ address }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.message || 'Failed to add property');
      }
      await loadData();
    } catch (err) {
      throw err;
    }
  };

  const handleRemoveProperty = async (id: string) => {
    try {
      const res = await fetch(`/hometitle/properties/${id}`, { method: 'DELETE' });
      if (!res.ok) return;
      await loadData();
    } catch {
      // Silently fail
    }
  };

  const handleMarkAlertRead = async (id: string) => {
    try {
      const res = await fetch(`/hometitle/alerts/${id}/read`, { method: 'PATCH' });
      if (!res.ok) return;
      setAlerts((prev) => prev.map((a) => (a.id === id ? { ...a, isRead: true } : a)));
    } catch {
      // Silently fail
    }
  };

  const handleScan = async () => {
    try {
      const res = await fetch('/hometitle/scan', { method: 'POST' });
      if (!res.ok) return;
      await loadData();
    } catch {
      // Silently fail
    }
  };

  const errorTitle = () => {
    if (error().includes('Premium')) return 'Upgrade Required';
    if (error().includes('subscription')) return 'Subscription Needed';
    return 'Dashboard Unavailable';
  };

  if (loading()) {
    return (
      <main class="dashboard-page">
        <div class="container">
          <div class="dashboard-header">
            <h1>Home Title Monitor</h1>
            <p class="dashboard-subtitle">Monitor your properties for title changes and alerts</p>
          </div>
          <div class="loading">Loading dashboard...</div>
        </div>
      </main>
    );
  }

  if (error()) {
    return (
      <main class="dashboard-page">
        <div class="container">
          <div class="dashboard-header">
            <h1>Home Title Monitor</h1>
            <p class="dashboard-subtitle">Monitor your properties for title changes and alerts</p>
          </div>
          <div class="error-banner">
            <h2>{errorTitle()}</h2>
            <p>{error()}</p>
          </div>
        </div>
      </main>
    );
  }

  const s = stats() || { monitoredProperties: 0, tier: 'free', isPremium: false, propertyLimit: 0, canAddMore: false, recentAlertCount: 0, criticalAlertCount: 0 };

  return (
    <main class="dashboard-page">
      <div class="container">
        <div class="dashboard-header">
          <div>
            <h1>Home Title Monitor</h1>
            <p class="dashboard-subtitle">Monitor your properties for title changes and alerts</p>
          </div>
          <div class="dashboard-actions">
            <span class="tier-badge tier-{s.tier}">{s.tier} tier</span>
            {s.isPremium && (
              <button class="btn-primary" onclick={handleScan}>
                Scan Now
              </button>
            )}
          </div>
        </div>

        <div class="dashboard-stats-grid">
          <StatCard
            title="Monitored Properties"
            value={s.monitoredProperties}
            icon={<span>&#x1F3E0;</span>}
            color="rgba(59, 130, 246, 0.1)"
          />
          <StatCard
            title="Recent Alerts"
            value={s.recentAlertCount}
            icon={<span>&#x1F514;</span>}
            color="rgba(249, 115, 22, 0.1)"
          />
          <StatCard
            title="Critical Alerts"
            value={s.criticalAlertCount}
            icon={<span>&#x26A0;</span>}
            color="rgba(239, 68, 68, 0.1)"
          />
          <StatCard
            title="Properties Remaining"
            value={s.canAddMore ? s.propertyLimit - s.monitoredProperties : 0}
            icon={<span>&#x1F4CB;</span>}
            color="rgba(34, 197, 94, 0.1)"
          />
        </div>

        <div class="dashboard-grid">
          <div class="dashboard-section">
            <div class="section-header">
              <h2>Monitored Properties</h2>
              <button class="btn-link" onclick={() => setShowAlerts(!showAlerts())}>
                {showAlerts() ? 'Show Properties' : 'View Alerts'}
              </button>
            </div>

            {showAlerts() ? (
              <AlertsList alerts={alerts()} onMarkRead={handleMarkAlertRead} />
            ) : (
              <>
                <AddPropertyForm
                  onAdd={handleAddProperty}
                  canAddMore={s.canAddMore}
                  limit={s.propertyLimit}
                  monitoredCount={s.monitoredProperties}
                />
                {properties().length === 0 ? (
                  <div class="empty-state">
                    <h2>No properties monitored</h2>
                    <p>Add your first property above to start monitoring for title changes.</p>
                  </div>
                ) : (
                <div class="properties-grid">
                    {properties().map((p) => (
                      <PropertyCard
                        id={p.id}
                        address={p.address}
                        status={p.status}
                        lastChange={p.lastChange}
                        alertCount={p.alertCount}
                        onRemove={handleRemoveProperty}
                      />
                    ))}
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </main>
  );
};

export default DashboardPage;
