import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import { useTheme } from "../context/ThemeContext";
import { api } from "../api";
import Modal from "../components/Modal";
import type { User, APIKey, APIKeyScopes } from "../types";

const SCOPE_OPTIONS: { key: keyof APIKeyScopes; label: string; permissions: ("read" | "write")[] }[] = [
  { key: "calendars", label: "Calendars", permissions: ["read", "write"] },
  { key: "events", label: "Events", permissions: ["read", "write"] },
  { key: "contacts", label: "Contacts", permissions: ["read", "write"] },
  { key: "availability", label: "Availability", permissions: ["read"] },
  { key: "booking", label: "Booking", permissions: ["write"] },
];

export default function SettingsPage() {
  const { user, loading: authLoading, refreshUser, logout } = useAuth();
  const { theme, toggle } = useTheme();
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<"general" | "calendars" | "notifications" | "api-keys" | "account">("general");
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [prefs, setPrefs] = useState<Partial<User>>({});

  // API Keys state
  const [apiKeys, setApiKeys] = useState<APIKey[]>([]);
  const [apiKeysLoading, setApiKeysLoading] = useState(false);
  const [createKeyModal, setCreateKeyModal] = useState(false);
  const [newKeyName, setNewKeyName] = useState("");
  const [newKeyScopes, setNewKeyScopes] = useState<APIKeyScopes>({
    calendars: ["read", "write"],
    events: ["read", "write"],
    contacts: ["read", "write"],
    availability: ["read"],
    booking: ["write"],
  });
  const [createdKey, setCreatedKey] = useState<APIKey | null>(null);
  const [revokingId, setRevokingId] = useState<string | null>(null);

  // Delete account state
  const [deleteConfirm, setDeleteConfirm] = useState("");
  const [deleting, setDeleting] = useState(false);

  useEffect(() => {
    if (user) {
      setPrefs({
        timezone: user.timezone,
        week_start_day: user.week_start_day,
        date_format: user.date_format,
        time_format: user.time_format,
        default_event_duration_minutes: user.default_event_duration_minutes,
        default_reminder_minutes: user.default_reminder_minutes,
        show_weekends: user.show_weekends,
        working_hours_start: user.working_hours_start,
        working_hours_end: user.working_hours_end,
        notifications_email: user.notifications_email,
      });
    }
  }, [user]);

  useEffect(() => {
    if (activeTab === "api-keys") {
      setApiKeysLoading(true);
      api
        .listApiKeys()
        .then((res) => setApiKeys(res.items))
        .catch(() => setMessage("Failed to load API keys"))
        .finally(() => setApiKeysLoading(false));
    }
  }, [activeTab]);

  const handleSave = async () => {
    setSaving(true);
    setMessage("");
    try {
      const data = await api.updateMe(prefs);
      await refreshUser();
      setMessage("Settings saved");
      setTimeout(() => setMessage(""), 2000);
    } catch (err: any) {
      setMessage(err.error || "Failed to save");
    } finally {
      setSaving(false);
    }
  };

  const handleCreateApiKey = async () => {
    if (!newKeyName.trim()) {
      setMessage("Name is required");
      return;
    }
    setSaving(true);
    setMessage("");
    try {
      const key = await api.createApiKey({ name: newKeyName.trim(), scopes: newKeyScopes });
      setCreatedKey(key);
      setApiKeys((prev) => [key, ...prev]);
      setCreateKeyModal(false);
      setNewKeyName("");
    } catch (err: any) {
      setMessage(err.error || "Failed to create API key");
    } finally {
      setSaving(false);
    }
  };

  const handleRevokeApiKey = async (id: string) => {
    setRevokingId(id);
    try {
      await api.revokeApiKey(id);
      setApiKeys((prev) => prev.map((k) => (k.id === id ? { ...k, revoked_at: new Date().toISOString() } : k)));
    } catch (err: any) {
      setMessage(err.error || "Failed to revoke");
    } finally {
      setRevokingId(null);
    }
  };

  const handleDeleteAccount = async () => {
    if (deleteConfirm !== "delete") return;
    setDeleting(true);
    setMessage("");
    try {
      await api.deleteMe();
      await logout();
      navigate("/login");
    } catch (err: any) {
      setMessage(err.error || "Failed to delete account");
    } finally {
      setDeleting(false);
    }
  };

  const copyToken = () => {
    if (createdKey?.token) {
      navigator.clipboard.writeText(createdKey.token);
      setMessage("Token copied to clipboard");
      setTimeout(() => setMessage(""), 2000);
    }
  };

  if (authLoading || !user) return null;

  const tabs = [
    { id: "general" as const, label: "General" },
    { id: "calendars" as const, label: "Calendars" },
    { id: "notifications" as const, label: "Notifications" },
    { id: "api-keys" as const, label: "API Keys" },
    { id: "account" as const, label: "Account" },
  ];

  return (
    <div className="h-full flex flex-col overflow-hidden">
      <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <h1 className="text-xl font-bold text-gray-900 dark:text-white">Settings</h1>
        <button
          onClick={toggle}
          className="p-2 rounded-xl hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400 transition-colors"
        >
          {theme === "dark" ? (
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
            </svg>
          ) : (
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
            </svg>
          )}
        </button>
      </div>

      <div className="flex flex-1 overflow-hidden">
        <nav className="w-48 border-r border-gray-200 dark:border-gray-700 p-4 flex-shrink-0">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setActiveTab(t.id)}
              className={`block w-full text-left px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                activeTab === t.id
                  ? "bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400"
                  : "text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800"
              }`}
            >
              {t.label}
            </button>
          ))}
        </nav>

        <main className="flex-1 overflow-y-auto p-6">
          {message && (
            <div
              className={`mb-4 px-4 py-2 rounded-lg text-sm ${
                message === "Settings saved" || message === "Token copied to clipboard"
                  ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400"
                  : "bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400"
              }`}
            >
              {message}
            </div>
          )}

          {activeTab === "general" && (
            <div className="space-y-6 max-w-xl">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">General</h2>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Timezone
                </label>
                <input
                  type="text"
                  value={prefs.timezone || ""}
                  onChange={(e) => setPrefs((p) => ({ ...p, timezone: e.target.value }))}
                  placeholder="America/New_York"
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Week starts on
                </label>
                <select
                  value={prefs.week_start_day ?? 0}
                  onChange={(e) => setPrefs((p) => ({ ...p, week_start_day: parseInt(e.target.value, 10) }))}
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                >
                  <option value={0}>Sunday</option>
                  <option value={1}>Monday</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Date format
                </label>
                <select
                  value={prefs.date_format || "MM/dd/yyyy"}
                  onChange={(e) => setPrefs((p) => ({ ...p, date_format: e.target.value }))}
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                >
                  <option value="MM/dd/yyyy">MM/DD/YYYY</option>
                  <option value="dd/MM/yyyy">DD/MM/YYYY</option>
                  <option value="yyyy-MM-dd">YYYY-MM-DD</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Time format
                </label>
                <select
                  value={prefs.time_format || "12h"}
                  onChange={(e) => setPrefs((p) => ({ ...p, time_format: e.target.value }))}
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                >
                  <option value="12h">12-hour</option>
                  <option value="24h">24-hour</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Default event duration (minutes)
                </label>
                <input
                  type="number"
                  min={15}
                  max={480}
                  value={prefs.default_event_duration_minutes ?? 60}
                  onChange={(e) =>
                    setPrefs((p) => ({
                      ...p,
                      default_event_duration_minutes: parseInt(e.target.value, 10) || 60,
                    }))
                  }
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Default reminder (minutes before)
                </label>
                <input
                  type="number"
                  min={0}
                  max={10080}
                  value={prefs.default_reminder_minutes ?? 10}
                  onChange={(e) =>
                    setPrefs((p) => ({
                      ...p,
                      default_reminder_minutes: parseInt(e.target.value, 10) || 10,
                    }))
                  }
                  className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                />
              </div>
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="show_weekends"
                  checked={prefs.show_weekends ?? true}
                  onChange={(e) => setPrefs((p) => ({ ...p, show_weekends: e.target.checked }))}
                  className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
                />
                <label htmlFor="show_weekends" className="text-sm text-gray-700 dark:text-gray-300">
                  Show weekends
                </label>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Working hours start
                  </label>
                  <input
                    type="time"
                    value={prefs.working_hours_start || "09:00"}
                    onChange={(e) => setPrefs((p) => ({ ...p, working_hours_start: e.target.value }))}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Working hours end
                  </label>
                  <input
                    type="time"
                    value={prefs.working_hours_end || "17:00"}
                    onChange={(e) => setPrefs((p) => ({ ...p, working_hours_end: e.target.value }))}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
                  />
                </div>
              </div>
            </div>
          )}

          {activeTab === "calendars" && (
            <div className="space-y-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Calendars</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                Manage your calendars from the main calendar view. Use the sidebar to add new
                calendars or add from URL.
              </p>
            </div>
          )}

          {activeTab === "notifications" && (
            <div className="space-y-6 max-w-xl">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Notifications</h2>
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="notifications_email"
                  checked={prefs.notifications_email ?? true}
                  onChange={(e) => setPrefs((p) => ({ ...p, notifications_email: e.target.checked }))}
                  className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
                />
                <label htmlFor="notifications_email" className="text-sm text-gray-700 dark:text-gray-300">
                  Email reminders for events
                </label>
              </div>
            </div>
          )}

          {activeTab === "api-keys" && (
            <div className="space-y-6 max-w-2xl">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">API Keys</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                API keys allow programmatic access to your calendar. Use them for integrations, scripts, or AI agents.
                Keep keys secure and never share them.
              </p>
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600 dark:text-gray-400">
                  {apiKeys.length} key{apiKeys.length !== 1 ? "s" : ""}
                </span>
                <button
                  onClick={() => {
                    setCreateKeyModal(true);
                    setCreatedKey(null);
                    setMessage("");
                  }}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors"
                >
                  Create API key
                </button>
              </div>
              {apiKeysLoading ? (
                <div className="flex items-center gap-2 text-gray-500 dark:text-gray-400">
                  <span className="w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin" />
                  Loading...
                </div>
              ) : (
                <div className="space-y-6 max-w-2xl">
                  {apiKeys.length === 0 ? (
                    <p className="text-sm text-gray-500 dark:text-gray-400 py-4">
                      No API keys yet. Create one to get started.
                    </p>
                  ) : (
                    <ul className="divide-y divide-gray-200 dark:divide-gray-700">
                      {apiKeys.map((key) => (
                        <li
                          key={key.id}
                          className="py-4 flex items-center justify-between gap-4"
                        >
                          <div className="flex-1 min-w-0">
                            <p className="font-medium text-gray-900 dark:text-white truncate">
                              {key.name}
                            </p>
                            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                              Created {new Date(key.created_at).toLocaleDateString()}
                              {key.revoked_at && (
                                <span className="ml-2 text-amber-600 dark:text-amber-400">
                                  • Revoked
                                </span>
                              )}
                            </p>
                          </div>
                          {!key.revoked_at && (
                            <button
                              onClick={() => handleRevokeApiKey(key.id)}
                              disabled={revokingId === key.id}
                              className="px-3 py-1.5 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50"
                            >
                              {revokingId === key.id ? "Revoking..." : "Revoke"}
                            </button>
                          )}
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              )}
            </div>
          )}

          {activeTab === "account" && (
            <div className="space-y-6 max-w-xl">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Account</h2>
              <div className="rounded-lg border border-gray-200 dark:border-gray-600 p-4 dark:bg-gray-800/50">
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                  Signed in as <span className="font-medium text-gray-900 dark:text-white">{user.email}</span>
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Account created {new Date(user.created_at).toLocaleDateString()}
                </p>
              </div>
              <div className="pt-6 border-t border-gray-200 dark:border-gray-700">
                <h3 className="text-sm font-medium text-red-600 dark:text-red-400 mb-2">
                  Danger zone
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  Deleting your account will permanently remove all your calendars, events, contacts,
                  and revoke all API keys. This action cannot be undone.
                </p>
                <div className="flex flex-wrap items-end gap-4">
                  <div className="flex-1 min-w-[200px]">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Type <span className="font-mono text-red-600 dark:text-red-400">delete</span> to confirm
                    </label>
                    <input
                      type="text"
                      value={deleteConfirm}
                      onChange={(e) => setDeleteConfirm(e.target.value)}
                      placeholder="delete"
                      className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-red-500 outline-none placeholder:text-gray-400"
                    />
                  </div>
                  <button
                    onClick={handleDeleteAccount}
                    disabled={deleteConfirm !== "delete" || deleting}
                    className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
                  >
                    {deleting ? "Deleting..." : "Delete account"}
                  </button>
                </div>
              </div>
            </div>
          )}

          {(activeTab === "general" || activeTab === "notifications") && (
            <div className="mt-8">
              <button
                onClick={handleSave}
                disabled={saving}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
              >
                {saving ? "Saving..." : "Save changes"}
              </button>
            </div>
          )}
        </main>
      </div>

      {/* Create API Key Modal */}
      <Modal
        open={createKeyModal}
        onClose={() => {
          setCreateKeyModal(false);
          setNewKeyName("");
        }}
        title="Create API key"
        wide
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Name
            </label>
            <input
              type="text"
              value={newKeyName}
              onChange={(e) => setNewKeyName(e.target.value)}
              placeholder="e.g. My integration"
              className="w-full px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Scopes
            </label>
            <div className="space-y-3">
              {SCOPE_OPTIONS.map(({ key, label, permissions }) => (
                <div key={key} className="flex items-center gap-4">
                  <span className="w-28 text-sm text-gray-600 dark:text-gray-400">{label}</span>
                  <div className="flex gap-4">
                    {permissions.map((perm) => {
                      const current = newKeyScopes[key] || [];
                      const checked = current.includes(perm);
                      return (
                        <label key={perm} className="flex items-center gap-1.5 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={checked}
                            onChange={(e) => {
                              const next = e.target.checked
                                ? [...(newKeyScopes[key] || []), perm]
                                : (newKeyScopes[key] || []).filter((p) => p !== perm);
                              setNewKeyScopes((s) => ({ ...s, [key]: next }));
                            }}
                            className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
                          />
                          <span className="text-sm text-gray-700 dark:text-gray-300 capitalize">{perm}</span>
                        </label>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button
              onClick={() => setCreateKeyModal(false)}
              className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleCreateApiKey}
              disabled={saving || !newKeyName.trim()}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
            >
              {saving ? "Creating..." : "Create"}
            </button>
          </div>
        </div>
      </Modal>

      {/* Token shown once modal */}
      <Modal
        open={!!createdKey?.token}
        onClose={() => setCreatedKey(null)}
        title="API key created"
      >
        <div className="space-y-4">
          <p className="text-sm text-amber-600 dark:text-amber-400">
            Copy this token now. It will not be shown again.
          </p>
          <div className="flex gap-2">
            <input
              type="text"
              readOnly
              value={createdKey?.token || ""}
              className="flex-1 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 text-sm font-mono text-gray-900 dark:text-white"
            />
            <button
              onClick={copyToken}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors"
            >
              Copy
            </button>
          </div>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            Use in requests: <code className="bg-gray-100 dark:bg-gray-700 px-1 rounded">X-API-Key: &lt;token&gt;</code>
          </p>
          <div className="flex justify-end">
            <button
              onClick={() => setCreatedKey(null)}
              className="px-4 py-2 bg-gray-200 dark:bg-gray-600 hover:bg-gray-300 dark:hover:bg-gray-500 text-gray-900 dark:text-white text-sm font-medium rounded-lg transition-colors"
            >
              Done
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
