"use client";

import { useState, useEffect } from "react";
import CountryDropdown from "@/components/shared/country-dropdown";
import CityDropdown from "@/components/shared/city-dropdown";

interface Alert {
  id: number;
  country_id: number;
  city_id: number;
  country_name: string;
  city_name: string;
  created_at: string;
}

export default function GeoFenceAlertsPage() {
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [countryId, setCountryId] = useState<number | null>(null);
  const [cityId, setCityId] = useState<number | null>(null);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

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

  async function fetchAlerts() {
    try {
      const res = await fetch("/api/alerts");
      const data = await res.json();
      setAlerts(data.alerts || []);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!countryId || !cityId) {
      setError("Please select both country and city.");
      return;
    }

    setSaving(true);
    setError("");
    setSuccess("");

    try {
      const res = await fetch("/api/alerts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ country_id: countryId, city_id: cityId }),
      });
      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "Failed to create alert");
        return;
      }

      setSuccess("Alert created! You will be notified when new escorts register in this city.");
      setCountryId(null);
      setCityId(null);
      fetchAlerts();
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(alertId: number) {
    try {
      await fetch(`/api/alerts?id=${alertId}`, { method: "DELETE" });
      setAlerts((prev) => prev.filter((a) => a.id !== alertId));
    } catch {
      // ignore
    }
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="flex items-center gap-3 mb-6">
        <svg className="w-6 h-6 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
        </svg>
        <div>
          <h1 className="text-2xl font-bold">Location Alerts</h1>
          <p className="text-text-muted text-sm">Get notified when new escorts register in your preferred cities</p>
        </div>
      </div>

      {/* Create Alert Form */}
      <div className="bg-surface rounded-lg p-6 mb-6">
        <h2 className="text-lg font-semibold mb-4">Create New Alert</h2>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Country</label>
            <CountryDropdown
              value={countryId}
              onChange={setCountryId}
              className="w-full"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">City</label>
            <CityDropdown
              countryId={countryId}
              value={cityId}
              onChange={setCityId}
              className="w-full"
            />
          </div>

          {error && (
            <p className="text-red-400 text-sm">{error}</p>
          )}
          {success && (
            <p className="text-green-400 text-sm">{success}</p>
          )}

          <button
            type="submit"
            disabled={saving || !countryId || !cityId}
            className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {saving ? "Creating..." : "Create Alert"}
          </button>
        </form>
      </div>

      {/* Existing Alerts */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">
          Your Alerts {!loading && `(${alerts.length})`}
        </h2>

        {loading ? (
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-14 bg-surface-light rounded-lg animate-pulse" />
            ))}
          </div>
        ) : alerts.length === 0 ? (
          <p className="text-text-muted text-sm py-4 text-center">
            No alerts yet. Create one above to get started.
          </p>
        ) : (
          <div className="space-y-2">
            {alerts.map((alert) => (
              <div
                key={alert.id}
                className="flex items-center justify-between bg-surface-light rounded-lg p-3"
              >
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                    <svg className="w-4 h-4 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                  </div>
                  <div>
                    <p className="font-medium text-sm">{alert.city_name}</p>
                    <p className="text-text-muted text-xs">{alert.country_name}</p>
                  </div>
                </div>
                <button
                  onClick={() => handleDelete(alert.id)}
                  className="text-text-muted hover:text-red-400 transition-colors p-1.5"
                  title="Delete alert"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
