"use client";

import { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";

interface EmergencyContact {
  type: "phone" | "email";
  value: string;
}

export default function SafetySettingsPage() {
  const { data: session } = useSession();
  const [contacts, setContacts] = useState<EmergencyContact[]>([
    { type: "phone", value: "" },
  ]);
  const [panicEnabled, setPanicEnabled] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [testSent, setTestSent] = useState(false);
  const [loading, setLoading] = useState(true);

  // Load settings on mount
  useEffect(() => {
    const storedPanic = localStorage.getItem("panic_gesture_enabled");
    if (storedPanic !== null) {
      setPanicEnabled(storedPanic !== "false");
    }

    async function loadSettings() {
      try {
        const res = await fetch("/api/safety/settings");
        if (res.ok) {
          const data = await res.json();
          if (data.contacts && data.contacts.length > 0) {
            setContacts(data.contacts);
          }
          if (data.panic_enabled !== undefined) {
            setPanicEnabled(data.panic_enabled);
          }
        }
      } catch {
        // Settings may not exist yet
      } finally {
        setLoading(false);
      }
    }

    loadSettings();
  }, []);

  function addContact() {
    if (contacts.length >= 3) return;
    setContacts([...contacts, { type: "phone", value: "" }]);
  }

  function removeContact(idx: number) {
    setContacts(contacts.filter((_, i) => i !== idx));
  }

  function updateContact(idx: number, field: "type" | "value", val: string) {
    setContacts(
      contacts.map((c, i) =>
        i === idx ? { ...c, [field]: val } : c
      )
    );
  }

  const handlePanicToggle = useCallback((enabled: boolean) => {
    setPanicEnabled(enabled);
    localStorage.setItem("panic_gesture_enabled", String(enabled));
  }, []);

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError(null);
    setSaved(false);

    // Persist panic gesture preference
    localStorage.setItem("panic_gesture_enabled", String(panicEnabled));

    try {
      const res = await fetch("/api/safety/settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contacts: contacts.filter((c) => c.value.trim()),
          panic_enabled: panicEnabled,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Failed to save settings");
        return;
      }

      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch {
      setError("Failed to save. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  async function handleTestPanic() {
    setTestSent(false);

    if (typeof navigator !== "undefined" && "geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(
        async (pos) => {
          await fetch("/api/safety/panic", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              latitude: pos.coords.latitude,
              longitude: pos.coords.longitude,
            }),
          });
          setTestSent(true);
          setTimeout(() => setTestSent(false), 3000);
        },
        async () => {
          await fetch("/api/safety/panic", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ latitude: 0, longitude: 0 }),
          });
          setTestSent(true);
          setTimeout(() => setTestSent(false), 3000);
        }
      );
    }
  }

  if (!session?.user) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="bg-surface rounded-lg p-8 text-center">
          <h1 className="text-2xl font-bold mb-4">Safety Settings</h1>
          <p className="text-text-muted mb-4">Please log in to configure safety settings.</p>
          <Link
            href="/login"
            className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors"
          >
            Log In
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-text mb-2">Safety Settings</h1>
        <p className="text-text-muted">
          Configure your emergency contacts and panic alert preferences.
        </p>
      </div>

      {loading ? (
        <div className="bg-surface rounded-lg p-8 text-center">
          <div className="animate-pulse text-text-muted">Loading settings...</div>
        </div>
      ) : (
        <form onSubmit={handleSave} className="space-y-6">
          {/* Emergency Contacts */}
          <div className="bg-surface rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h2 className="text-lg font-semibold">Emergency Contacts</h2>
                <p className="text-text-muted text-sm mt-1">
                  Up to 3 contacts who will be alerted if you trigger a panic alert.
                </p>
              </div>
              {contacts.length < 3 && (
                <button
                  type="button"
                  onClick={addContact}
                  className="text-gold hover:text-gold/80 text-sm font-medium transition-colors flex items-center gap-1"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                  </svg>
                  Add
                </button>
              )}
            </div>

            <div className="space-y-3">
              {contacts.map((contact, idx) => (
                <div key={idx} className="flex items-center gap-2">
                  <select
                    value={contact.type}
                    onChange={(e) => updateContact(idx, "type", e.target.value)}
                    className="bg-background border border-surface-light rounded-lg px-3 py-2.5 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                  >
                    <option value="phone">Phone</option>
                    <option value="email">Email</option>
                  </select>
                  <input
                    type={contact.type === "phone" ? "tel" : "email"}
                    value={contact.value}
                    onChange={(e) => updateContact(idx, "value", e.target.value)}
                    placeholder={
                      contact.type === "phone"
                        ? "+44 7XXX XXXXXX"
                        : "contact@example.com"
                    }
                    className="flex-1 bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                  {contacts.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeContact(idx)}
                      className="text-red-400 hover:text-red-300 p-2 transition-colors"
                    >
                      <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>

          {/* Panic Gesture */}
          <div className="bg-surface rounded-lg p-6">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-lg font-semibold">Panic Gesture</h2>
                <p className="text-text-muted text-sm mt-1">
                  Triple-tap anywhere on screen within 1 second to trigger a silent alert.
                </p>
              </div>
              <button
                type="button"
                onClick={() => handlePanicToggle(!panicEnabled)}
                className={`relative inline-flex h-7 w-12 items-center rounded-full transition-colors ${
                  panicEnabled ? "bg-green-500" : "bg-surface-light"
                }`}
              >
                <span
                  className={`inline-block h-5 w-5 rounded-full bg-white transition-transform ${
                    panicEnabled ? "translate-x-6" : "translate-x-1"
                  }`}
                />
              </button>
            </div>
          </div>

          {/* Test Panic Alert */}
          <div className="bg-surface rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-2">Test Panic Alert</h2>
            <p className="text-text-muted text-sm mb-4">
              Send a test alert to verify your setup is working. This will log a test panic event
              but will not notify your emergency contacts.
            </p>
            <button
              type="button"
              onClick={handleTestPanic}
              className="bg-red-600/20 hover:bg-red-600/30 text-red-400 border border-red-600/30 px-4 py-2 rounded-lg text-sm font-semibold transition-colors"
            >
              {testSent ? "Test Alert Sent" : "Send Test Alert"}
            </button>
            {testSent && (
              <p className="text-green-400 text-sm mt-2">
                Test panic alert logged successfully.
              </p>
            )}
          </div>

          {/* Quick Links */}
          <div className="bg-surface rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">Safety Tools</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <Link
                href="/safety/verify"
                className="flex items-center gap-3 bg-surface-light hover:bg-surface-light/80 rounded-lg p-4 transition-colors"
              >
                <svg className="w-6 h-6 text-gold shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
                <div>
                  <p className="font-medium text-sm">Mutual Verification</p>
                  <p className="text-text-muted text-xs">Verify before meeting</p>
                </div>
              </Link>
              <Link
                href="/safety/report"
                className="flex items-center gap-3 bg-surface-light hover:bg-surface-light/80 rounded-lg p-4 transition-colors"
              >
                <svg className="w-6 h-6 text-gold shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 21v-4m0 0V5a2 2 0 012-2h6.5l1 1H21l-3 6 3 6h-8.5l-1-1H5a2 2 0 00-2 2zm9-13.5V9" />
                </svg>
                <div>
                  <p className="font-medium text-sm">Incident Report</p>
                  <p className="text-text-muted text-xs">File a safety report</p>
                </div>
              </Link>
              <Link
                href="/safety/checkin"
                className="flex items-center gap-3 bg-surface-light hover:bg-surface-light/80 rounded-lg p-4 transition-colors"
              >
                <svg className="w-6 h-6 text-gold shrink-0" 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>
                  <p className="font-medium text-sm">Safety Check-In</p>
                  <p className="text-text-muted text-xs">Timed safety check-ins</p>
                </div>
              </Link>
              <Link
                href="/safety"
                className="flex items-center gap-3 bg-surface-light hover:bg-surface-light/80 rounded-lg p-4 transition-colors"
              >
                <svg className="w-6 h-6 text-gold shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                </svg>
                <div>
                  <p className="font-medium text-sm">Safety Resources</p>
                  <p className="text-text-muted text-xs">Tips and emergency info</p>
                </div>
              </Link>
            </div>
          </div>

          {/* Save */}
          {error && (
            <div className="bg-red-900/20 border border-red-800 rounded-lg p-4">
              <p className="text-red-400 text-sm">{error}</p>
            </div>
          )}

          {saved && (
            <div className="bg-green-900/20 border border-green-800 rounded-lg p-4">
              <p className="text-green-400 text-sm">Settings saved successfully.</p>
            </div>
          )}

          <button
            type="submit"
            disabled={saving}
            className="w-full bg-primary hover:bg-primary-dark text-white py-3 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {saving ? "Saving..." : "Save Settings"}
          </button>
        </form>
      )}
    </div>
  );
}
