"use client";

import {
  X,
  User,
  Clock,
  FileText,
  CreditCard,
  Shield,
  Link2,
  Settings2,
} from "lucide-react";
import { useState, useEffect } from "react";

import {
  UserModalProps,
  TabType,
  LoginHistoryEntry,
  AdminNote,
  BillingEmail,
  StripeInvoice,
  InvoiceSummary,
  UserLink,
  IntegrationsState,
  LinkFormState,
} from "./types";

import { OverviewTab } from "./OverviewTab";
import { HistoryTab } from "./HistoryTab";
import { NotesTab } from "./NotesTab";
import { BillingTab } from "./BillingTab";
import { LinksTab } from "./LinksTab";
import { IntegrationsTab } from "./IntegrationsTab";
import { ActionsTab } from "./ActionsTab";

export function UserModal({
  user,
  onClose,
  onSuspend,
  onActivate,
  isAdmin,
}: UserModalProps) {
  const [activeTab, setActiveTab] = useState<TabType>("overview");
  const [copiedText, setCopiedText] = useState<string | null>(null);
  const [newNote, setNewNote] = useState("");
  const [noteCategory, setNoteCategory] =
    useState<AdminNote["category"]>("general");
  const [billingSubject, setBillingSubject] = useState("");
  const [billingMessage, setBillingMessage] = useState("");
  const [billingAmount, setBillingAmount] = useState("");
  const [billingCurrency, setBillingCurrency] = useState("GBP");
  const [billingDueDate, setBillingDueDate] = useState("");
  const [includePaymentLink, setIncludePaymentLink] = useState(true);
  const [suspendReason, setSuspendReason] = useState("");
  const [trialExtensionWeeks, setTrialExtensionWeeks] = useState(2);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  // Real data from API
  const [loginHistory, setLoginHistory] = useState<LoginHistoryEntry[]>([]);
  const [adminNotes, setAdminNotes] = useState<AdminNote[]>([]);
  const [billingEmails, setBillingEmails] = useState<BillingEmail[]>([]);
  const [userDetails, setUserDetails] = useState<Record<
    string,
    unknown
  > | null>(null);
  const [userLinks, setUserLinks] = useState<UserLink[]>([]);

  // Invoice history state
  const [invoices, setInvoices] = useState<StripeInvoice[]>([]);
  const [invoiceSummary, setInvoiceSummary] = useState<InvoiceSummary | null>(
    null,
  );
  const [loadingInvoices, setLoadingInvoices] = useState(false);
  const [showAllInvoices, setShowAllInvoices] = useState(false);

  // Link form state
  const [showLinkForm, setShowLinkForm] = useState(false);
  const [editingLink, setEditingLink] = useState<UserLink | null>(null);
  const [linkForm, setLinkForm] = useState<LinkFormState>({
    linkType: "CUSTOM",
    title: "",
    url: "",
    description: "",
  });

  // Integrations state
  const [integrations, setIntegrations] = useState<IntegrationsState>({
    n8nWebhookToken: "",
    voiceAgentId: "",
    voiceAgentConfig: {},
  });
  const [generatingToken, setGeneratingToken] = useState(false);

  // Fetch user details on mount
  useEffect(() => {
    if (user) {
      fetchUserDetails();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id]);

  async function fetchUserDetails() {
    try {
      setLoading(true);
      const response = await fetch(`/api/staff/users/${user?.id}`);
      if (response.ok) {
        const data = await response.json();
        setUserDetails(data.user);
        setLoginHistory(
          data.user.login_history
            ?.slice(0, 20)
            .map((l: Record<string, unknown>) => ({
              id: l.id,
              ipAddress: l.ipAddress,
              country: l.country,
              city: l.city,
              timestamp: l.createdAt,
              logoutAt: l.logoutAt,
              userAgent: l.userAgent,
              provider: l.provider || "credentials",
              success: l.success !== false,
            })) || [],
        );
        setAdminNotes(
          data.user.admin_notes?.map((n: Record<string, unknown>) => ({
            id: n.id,
            category: (n.category as string).toLowerCase(),
            content: n.content,
            createdBy: n.staffId,
            createdAt: n.createdAt,
          })) || [],
        );
        setBillingEmails(
          data.user.billing_emails?.map((e: Record<string, unknown>) => ({
            id: e.id,
            subject: e.subject,
            sentAt: e.sentAt,
            status: (e.status as string).toLowerCase(),
          })) || [],
        );
        setUserLinks(
          data.user.user_links?.map((l: Record<string, unknown>) => ({
            id: l.id,
            linkType: l.linkType,
            title: l.title,
            url: l.url,
            description: l.description,
            icon: l.icon,
            isActive: l.isActive,
            sortOrder: l.sortOrder,
            createdAt: l.createdAt,
          })) || [],
        );

        // Set integrations data
        setIntegrations({
          n8nWebhookToken: (data.user.n8nWebhookToken as string) || "",
          voiceAgentId: (data.user.voiceAgentId as string) || "",
          voiceAgentConfig:
            (data.user.voiceAgentConfig as Record<string, string>) || {},
        });

        // Fetch invoices for non-team members
        if (!data.user.isTeamMember) {
          fetchInvoices();
        }
      }
    } catch (error) {
      console.error("Failed to fetch user details:", error);
    } finally {
      setLoading(false);
    }
  }

  async function fetchInvoices() {
    if (!user?.id) return;

    try {
      setLoadingInvoices(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/billing/invoices`,
      );
      if (response.ok) {
        const data = await response.json();
        setInvoices(data.invoices || []);
        setInvoiceSummary(data.summary || null);
      }
    } catch (error) {
      console.error("Failed to fetch invoices:", error);
    } finally {
      setLoadingInvoices(false);
    }
  }

  if (!user) return null;

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedText(text);
      setTimeout(() => setCopiedText(null), 2000);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

  const allTabs: {
    id: TabType;
    label: string;
    icon: React.ComponentType<{ className?: string }>;
  }[] = [
    { id: "overview", label: "Overview", icon: User },
    { id: "history", label: "Session Activity", icon: Clock },
    { id: "notes", label: "Admin Notes", icon: FileText },
    { id: "billing", label: "Billing", icon: CreditCard },
    { id: "links", label: "Links", icon: Link2 },
    { id: "integrations", label: "Integrations", icon: Settings2 },
    { id: "actions", label: "Actions", icon: Shield },
  ];

  // Filter out Links and Integrations tabs for team members
  const tabs = userDetails?.isTeamMember
    ? allTabs.filter((tab) => !["links", "integrations"].includes(tab.id))
    : allTabs;

  // API Handlers
  const handleSendBillingEmail = async () => {
    if (!billingSubject.trim() || !billingMessage.trim()) {
      alert("Please fill in both subject and message");
      return;
    }

    if (
      includePaymentLink &&
      (!billingAmount || parseFloat(billingAmount) <= 0)
    ) {
      alert("Please enter an amount when including a payment link");
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/billing/email`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            subject: billingSubject,
            content: billingMessage,
            amount: billingAmount ? parseFloat(billingAmount) : undefined,
            currency: billingCurrency,
            dueDate: billingDueDate || undefined,
            includePaymentLink,
          }),
        },
      );

      if (response.ok) {
        const data = await response.json();
        const message = data.billingEmail?.paymentUrl
          ? "Billing email with payment link sent successfully!"
          : "Billing email sent successfully";
        alert(message);
        setBillingSubject("");
        setBillingMessage("");
        setBillingAmount("");
        setBillingDueDate("");
        setIncludePaymentLink(true);
        fetchUserDetails();
        fetchInvoices();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to send email");
      }
    } catch (error) {
      console.error("Failed to send billing email:", error);
      alert("Failed to send email");
    } finally {
      setSubmitting(false);
    }
  };

  const handleAddNote = async () => {
    if (!newNote.trim()) return;

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/notes`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          content: newNote,
          category: noteCategory.toUpperCase(),
        }),
      });

      if (response.ok) {
        setNewNote("");
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to add note");
      }
    } catch (error) {
      console.error("Failed to add note:", error);
      alert("Failed to add note");
    } finally {
      setSubmitting(false);
    }
  };

  const handleSuspend = async () => {
    if (!suspendReason.trim() || suspendReason.length < 5) {
      alert("Please provide a reason (minimum 5 characters)");
      return;
    }

    if (!confirm("Are you sure you want to suspend this account?")) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "suspend",
          reason: suspendReason,
        }),
      });

      if (response.ok) {
        alert("Account suspended successfully");
        setSuspendReason("");
        onSuspend?.(user.id, suspendReason);
        onClose();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to suspend account");
      }
    } catch (error) {
      console.error("Failed to suspend account:", error);
      alert("Failed to suspend account");
    } finally {
      setSubmitting(false);
    }
  };

  const handleActivate = async () => {
    if (!confirm("Are you sure you want to activate this account?")) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "activate",
          reason: "Account reactivated by administrator",
        }),
      });

      if (response.ok) {
        alert("Account activated successfully");
        onActivate?.(user.id);
        onClose();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to activate account");
      }
    } catch (error) {
      console.error("Failed to activate account:", error);
      alert("Failed to activate account");
    } finally {
      setSubmitting(false);
    }
  };

  const handleExtendTrial = async () => {
    if (!confirm(`Extend trial by ${trialExtensionWeeks} weeks?`)) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/extend-trial`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          weeks: trialExtensionWeeks,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        alert(
          `Trial extended successfully! New trial end date: ${new Date(data.newTrialEnd).toLocaleDateString()}`,
        );
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to extend trial");
      }
    } catch (error) {
      console.error("Failed to extend trial:", error);
      alert("Failed to extend trial");
    } finally {
      setSubmitting(false);
    }
  };

  // Link handlers
  const resetLinkForm = () => {
    setLinkForm({
      linkType: "CUSTOM",
      title: "",
      url: "",
      description: "",
    });
    setEditingLink(null);
    setShowLinkForm(false);
  };

  const handleAddLink = async () => {
    if (!linkForm.title.trim() || !linkForm.url.trim()) {
      alert("Please fill in both title and URL");
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/links`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          linkType: linkForm.linkType,
          title: linkForm.title,
          url: linkForm.url,
          description: linkForm.description || null,
        }),
      });

      if (response.ok) {
        resetLinkForm();
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to add link");
      }
    } catch (error) {
      console.error("Failed to add link:", error);
      alert("Failed to add link");
    } finally {
      setSubmitting(false);
    }
  };

  const handleUpdateLink = async () => {
    if (!editingLink || !linkForm.title.trim() || !linkForm.url.trim()) {
      alert("Please fill in both title and URL");
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/links/${editingLink.id}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            linkType: linkForm.linkType,
            title: linkForm.title,
            url: linkForm.url,
            description: linkForm.description || null,
          }),
        },
      );

      if (response.ok) {
        resetLinkForm();
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to update link");
      }
    } catch (error) {
      console.error("Failed to update link:", error);
      alert("Failed to update link");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteLink = async (linkId: string) => {
    if (!confirm("Are you sure you want to delete this link?")) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/links/${linkId}`,
        {
          method: "DELETE",
        },
      );

      if (response.ok) {
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to delete link");
      }
    } catch (error) {
      console.error("Failed to delete link:", error);
      alert("Failed to delete link");
    } finally {
      setSubmitting(false);
    }
  };

  const startEditLink = (link: UserLink) => {
    setEditingLink(link);
    setLinkForm({
      linkType: link.linkType,
      title: link.title,
      url: link.url,
      description: link.description || "",
    });
    setShowLinkForm(true);
  };

  // Integration handlers
  const handleGenerateToken = async () => {
    if (
      !confirm(
        "Generate a new N8N webhook token? This will invalidate the current token if one exists.",
      )
    ) {
      return;
    }

    try {
      setGeneratingToken(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/integrations/generate-token`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
        },
      );

      if (response.ok) {
        const data = await response.json();
        setIntegrations((prev) => ({ ...prev, n8nWebhookToken: data.token }));
        alert("Token generated successfully!");
      } else {
        const error = await response.json();
        alert(error.error || "Failed to generate token");
      }
    } catch (error) {
      console.error("Failed to generate token:", error);
      alert("Failed to generate token");
    } finally {
      setGeneratingToken(false);
    }
  };

  const handleSaveIntegrations = async () => {
    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/integrations`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          voiceAgentId: integrations.voiceAgentId || null,
          voiceAgentConfig: integrations.voiceAgentConfig,
        }),
      });

      if (response.ok) {
        alert("Integration settings saved successfully!");
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to save integration settings");
      }
    } catch (error) {
      console.error("Failed to save integrations:", error);
      alert("Failed to save integration settings");
    } finally {
      setSubmitting(false);
    }
  };

  const handleRevokeToken = async () => {
    if (
      !confirm(
        "Revoke the N8N webhook token? This will disable all N8N integrations for this user.",
      )
    ) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/integrations/revoke-token`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
        },
      );

      if (response.ok) {
        setIntegrations((prev) => ({ ...prev, n8nWebhookToken: "" }));
        alert("Token revoked successfully!");
      } else {
        const error = await response.json();
        alert(error.error || "Failed to revoke token");
      }
    } catch (error) {
      console.error("Failed to revoke token:", error);
      alert("Failed to revoke token");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div>
            <h2 className="text-2xl font-bold text-brand-ink">{user.name}</h2>
            <p className="text-sm text-gray-600 mt-1">{user.email}</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition"
            aria-label="Close modal"
          >
            <X className="w-6 h-6 text-gray-500" />
          </button>
        </div>

        {/* Tabs */}
        <div className="border-b border-gray-200 overflow-hidden">
          <div
            className="flex overflow-x-auto pb-px -mb-px"
            style={{ scrollbarWidth: "thin" }}
          >
            {tabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex items-center gap-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition flex-shrink-0 ${
                    activeTab === tab.id
                      ? "text-brand-green border-b-2 border-brand-green"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {tab.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-green"></div>
            </div>
          ) : (
            <>
              {activeTab === "overview" && (
                <OverviewTab
                  user={user}
                  userDetails={userDetails}
                  loginHistory={loginHistory}
                  copiedText={copiedText}
                  onCopyToClipboard={copyToClipboard}
                  onNavigateToHistory={() => setActiveTab("history")}
                />
              )}

              {activeTab === "history" && (
                <HistoryTab
                  loginHistory={loginHistory}
                  copiedText={copiedText}
                  onCopyToClipboard={copyToClipboard}
                />
              )}

              {activeTab === "notes" && (
                <NotesTab
                  adminNotes={adminNotes}
                  newNote={newNote}
                  noteCategory={noteCategory}
                  submitting={submitting}
                  onNewNoteChange={setNewNote}
                  onNoteCategoryChange={setNoteCategory}
                  onAddNote={handleAddNote}
                />
              )}

              {activeTab === "billing" && (
                <BillingTab
                  userId={user.id}
                  userDetails={userDetails}
                  invoices={invoices}
                  invoiceSummary={invoiceSummary}
                  loadingInvoices={loadingInvoices}
                  showAllInvoices={showAllInvoices}
                  billingEmails={billingEmails}
                  billingSubject={billingSubject}
                  billingMessage={billingMessage}
                  billingAmount={billingAmount}
                  billingCurrency={billingCurrency}
                  billingDueDate={billingDueDate}
                  includePaymentLink={includePaymentLink}
                  submitting={submitting}
                  onFetchInvoices={fetchInvoices}
                  onShowAllInvoicesChange={setShowAllInvoices}
                  onBillingSubjectChange={setBillingSubject}
                  onBillingMessageChange={setBillingMessage}
                  onBillingAmountChange={setBillingAmount}
                  onBillingCurrencyChange={setBillingCurrency}
                  onBillingDueDateChange={setBillingDueDate}
                  onIncludePaymentLinkChange={setIncludePaymentLink}
                  onSendBillingEmail={handleSendBillingEmail}
                />
              )}

              {activeTab === "links" && (
                <LinksTab
                  userLinks={userLinks}
                  showLinkForm={showLinkForm}
                  editingLink={editingLink}
                  linkForm={linkForm}
                  submitting={submitting}
                  copiedText={copiedText}
                  onShowLinkFormChange={setShowLinkForm}
                  onLinkFormChange={setLinkForm}
                  onAddLink={handleAddLink}
                  onUpdateLink={handleUpdateLink}
                  onDeleteLink={handleDeleteLink}
                  onStartEditLink={startEditLink}
                  onResetLinkForm={resetLinkForm}
                  onCopyToClipboard={copyToClipboard}
                />
              )}

              {activeTab === "integrations" && (
                <IntegrationsTab
                  integrations={integrations}
                  submitting={submitting}
                  generatingToken={generatingToken}
                  copiedText={copiedText}
                  onIntegrationsChange={setIntegrations}
                  onGenerateToken={handleGenerateToken}
                  onRevokeToken={handleRevokeToken}
                  onSaveIntegrations={handleSaveIntegrations}
                  onCopyToClipboard={copyToClipboard}
                />
              )}

              {activeTab === "actions" && (
                <ActionsTab
                  user={user}
                  userDetails={userDetails}
                  isAdmin={isAdmin}
                  suspendReason={suspendReason}
                  trialExtensionWeeks={trialExtensionWeeks}
                  submitting={submitting}
                  onSuspendReasonChange={setSuspendReason}
                  onTrialExtensionWeeksChange={setTrialExtensionWeeks}
                  onSuspend={handleSuspend}
                  onActivate={handleActivate}
                  onExtendTrial={handleExtendTrial}
                />
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

// Default export for backwards compatibility
export default UserModal;
