"use client";

import { useState } from "react";
import {
  Search,
  Mail,
  Phone,
  Calendar,
  Shield,
  Activity,
  Loader2,
  AlertCircle,
} from "lucide-react";
import type { UserLookupResult } from "@/lib/types/admin-panel";

export function UserLookupClient() {
  const [query, setQuery] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<UserLookupResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!query.trim()) return;

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const res = await fetch(
        `/api/staff/admin/user-lookup?query=${encodeURIComponent(query)}`,
      );
      const data = await res.json();

      if (!res.ok) {
        setError(data.error || "User not found");
        return;
      }

      setResult(data);
    } catch {
      setError("Failed to search for user");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Search Form */}
      <form
        onSubmit={handleSearch}
        className="bg-white border border-gray-200 rounded-lg p-6"
      >
        <label className="block text-sm font-medium text-gray-700 mb-2">
          Search by email, phone, or user ID
        </label>
        <div className="flex gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="user@example.com or +1234567890 or user-id..."
              className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary focus:border-transparent"
            />
          </div>
          <button
            type="submit"
            disabled={loading || !query.trim()}
            className="px-6 py-3 bg-brand-primary text-white font-medium rounded-lg hover:bg-brand-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition flex items-center gap-2"
          >
            {loading ? (
              <Loader2 className="w-5 h-5 animate-spin" />
            ) : (
              <Search className="w-5 h-5" />
            )}
            Search
          </button>
        </div>
      </form>

      {/* Error State */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3">
          <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
          <p className="text-red-700">{error}</p>
        </div>
      )}

      {/* Results */}
      {result && (
        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
          {/* User Header */}
          <div className="px-6 py-5 bg-gradient-to-r from-gray-50 to-white border-b">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="w-14 h-14 bg-gradient-to-br from-brand-primary to-emerald-600 rounded-full flex items-center justify-center">
                  <span className="text-xl font-bold text-white">
                    {result.name?.charAt(0).toUpperCase() || "?"}
                  </span>
                </div>
                <div>
                  <h3 className="text-xl font-bold text-gray-900">
                    {result.name || "No Name"}
                  </h3>
                  <p className="text-sm text-gray-500">{result.email}</p>
                </div>
              </div>
              <span
                className={`px-3 py-1 rounded-full text-sm font-medium ${
                  result.isActive
                    ? "bg-green-100 text-green-800"
                    : "bg-red-100 text-red-800"
                }`}
              >
                {result.isActive ? "Active" : "Inactive"}
              </span>
            </div>
          </div>

          {/* User Details */}
          <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-4">
              <h4 className="text-sm font-semibold text-gray-500 uppercase tracking-wide">
                Account Info
              </h4>

              <div className="flex items-center gap-3">
                <Mail className="w-4 h-4 text-gray-400" />
                <span className="text-gray-900">{result.email}</span>
              </div>

              {result.phone && (
                <div className="flex items-center gap-3">
                  <Phone className="w-4 h-4 text-gray-400" />
                  <span className="text-gray-900">{result.phone}</span>
                </div>
              )}

              <div className="flex items-center gap-3">
                <Calendar className="w-4 h-4 text-gray-400" />
                <span className="text-gray-900">
                  Joined {new Date(result.createdAt).toLocaleDateString()}
                </span>
              </div>

              {result.lastLoginAt && (
                <div className="flex items-center gap-3">
                  <Activity className="w-4 h-4 text-gray-400" />
                  <span className="text-gray-900">
                    Last login: {new Date(result.lastLoginAt).toLocaleString()}
                  </span>
                </div>
              )}
            </div>

            <div className="space-y-4">
              <h4 className="text-sm font-semibold text-gray-500 uppercase tracking-wide">
                Subscription
              </h4>

              {result.subscriptionTier ? (
                <>
                  <div className="flex items-center gap-3">
                    <Shield className="w-4 h-4 text-gray-400" />
                    <span className="font-medium text-brand-primary capitalize">
                      {result.subscriptionTier}
                    </span>
                  </div>
                  <div className="text-sm text-gray-600">
                    Status:{" "}
                    <span className="font-medium capitalize">
                      {result.subscriptionStatus || "N/A"}
                    </span>
                  </div>
                  {result.trialEndsAt && (
                    <div className="text-sm text-gray-600">
                      Trial ends:{" "}
                      {new Date(result.trialEndsAt).toLocaleDateString()}
                    </div>
                  )}
                </>
              ) : (
                <p className="text-gray-500">No active subscription</p>
              )}
            </div>
          </div>

          {/* Feature Flags */}
          {result.featureFlags && (
            <div className="px-6 pb-6">
              <h4 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
                Features
              </h4>
              <div className="flex flex-wrap gap-2">
                <FeatureBadge
                  label="WhatsApp"
                  enabled={result.featureFlags.whatsappConnected}
                />
                <FeatureBadge
                  label="Voice Agent"
                  enabled={result.featureFlags.voiceAgentConfigured}
                />
                <FeatureBadge
                  label="Knowledge Base"
                  enabled={result.featureFlags.knowledgeBaseEnabled}
                />
              </div>
            </div>
          )}

          {/* Recent Sessions */}
          {result.recentSessions && result.recentSessions.length > 0 && (
            <div className="px-6 pb-6">
              <h4 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">
                Recent Sessions
              </h4>
              <div className="space-y-2">
                {result.recentSessions.slice(0, 3).map((session) => (
                  <div
                    key={session.id}
                    className="text-sm p-3 bg-gray-50 rounded-lg"
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-gray-600">
                        {session.ipAddress || "Unknown IP"}
                      </span>
                      <span className="text-gray-500">
                        {new Date(session.createdAt).toLocaleString()}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* User ID */}
          <div className="px-6 py-4 bg-gray-50 border-t">
            <p className="text-xs text-gray-500 font-mono">ID: {result.id}</p>
          </div>
        </div>
      )}
    </div>
  );
}

function FeatureBadge({ label, enabled }: { label: string; enabled: boolean }) {
  return (
    <span
      className={`px-3 py-1 rounded-full text-xs font-medium ${
        enabled ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-500"
      }`}
    >
      {label}: {enabled ? "Yes" : "No"}
    </span>
  );
}
