"use client";

import {
  Users,
  Receipt,
  RefreshCw,
  ExternalLink,
  Download,
  ChevronDown,
  ChevronUp,
  Mail,
  DollarSign,
  Calendar,
  CreditCard,
} from "lucide-react";
import {
  BillingEmail,
  StripeInvoice,
  InvoiceSummary,
  CURRENCY_OPTIONS,
} from "./types";

interface Subscription {
  id: string;
  tierId: string;
  status: string;
  billingPeriod?: string;
  currentPeriodEnd?: string;
  cardBrand?: string;
  cardLastFour?: string;
  lastPaymentDate?: string;
  trialEndsAt?: string;
  cancelAtPeriodEnd?: boolean;
}

interface TeamMembership {
  organizationName: string;
  owner?: { name: string; email: string };
}

interface BillingTabProps {
  userId: string;
  userDetails: Record<string, unknown> | null;
  invoices: StripeInvoice[];
  invoiceSummary: InvoiceSummary | null;
  loadingInvoices: boolean;
  showAllInvoices: boolean;
  billingEmails: BillingEmail[];
  billingSubject: string;
  billingMessage: string;
  billingAmount: string;
  billingCurrency: string;
  billingDueDate: string;
  includePaymentLink: boolean;
  submitting: boolean;
  onFetchInvoices: () => void;
  onShowAllInvoicesChange: (show: boolean) => void;
  onBillingSubjectChange: (value: string) => void;
  onBillingMessageChange: (value: string) => void;
  onBillingAmountChange: (value: string) => void;
  onBillingCurrencyChange: (value: string) => void;
  onBillingDueDateChange: (value: string) => void;
  onIncludePaymentLinkChange: (value: boolean) => void;
  onSendBillingEmail: () => void;
}

export function BillingTab({
  userDetails,
  invoices,
  invoiceSummary,
  loadingInvoices,
  showAllInvoices,
  billingEmails,
  billingSubject,
  billingMessage,
  billingAmount,
  billingCurrency,
  billingDueDate,
  includePaymentLink,
  submitting,
  onFetchInvoices,
  onShowAllInvoicesChange,
  onBillingSubjectChange,
  onBillingMessageChange,
  onBillingAmountChange,
  onBillingCurrencyChange,
  onBillingDueDateChange,
  onIncludePaymentLinkChange,
  onSendBillingEmail,
}: BillingTabProps) {
  const isTeamMember = Boolean(userDetails?.isTeamMember);
  const teamMembership = userDetails?.teamMembership as
    | TeamMembership
    | undefined;
  const subscriptions = (userDetails?.subscriptions as Subscription[]) || [];

  return (
    <div className="space-y-6">
      {/* Team Member Notice */}
      {isTeamMember && (
        <div className="p-6 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-blue-100 rounded-lg">
              <Users className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-brand-ink">
                Team Member
              </h3>
              <p className="text-sm text-gray-600">
                Billing is managed by the organization owner
              </p>
            </div>
          </div>
          <div className="p-4 bg-white/50 border border-blue-200 rounded-lg">
            <p className="text-sm text-gray-700 mb-2">
              This user is a member of{" "}
              <strong>{teamMembership?.organizationName ?? ""}</strong>.
            </p>
            <p className="text-sm text-gray-600">
              Subscription and billing are handled by the organization owner:
              <strong className="ml-1">{teamMembership?.owner?.name}</strong>
              <span className="text-gray-500 ml-1">
                ({teamMembership?.owner?.email})
              </span>
            </p>
          </div>
        </div>
      )}

      {/* Subscription Information - Only for non-team-members */}
      {!isTeamMember && subscriptions.length > 0 && (
        <SubscriptionSection subscription={subscriptions[0]} />
      )}

      {/* No subscription message - Only for non-team-members */}
      {!isTeamMember && subscriptions.length === 0 && (
        <div className="p-4 bg-gray-50 border border-gray-200 rounded-lg">
          <p className="text-sm text-gray-600">No active subscription</p>
        </div>
      )}

      {/* Invoice History - Only for non-team-members */}
      {!isTeamMember && (
        <InvoiceHistorySection
          invoices={invoices}
          invoiceSummary={invoiceSummary}
          loadingInvoices={loadingInvoices}
          showAllInvoices={showAllInvoices}
          onFetchInvoices={onFetchInvoices}
          onShowAllInvoicesChange={onShowAllInvoicesChange}
        />
      )}

      {/* Send Billing Email with Payment Link - Only for non-team-members */}
      {!isTeamMember && (
        <BillingEmailForm
          billingSubject={billingSubject}
          billingMessage={billingMessage}
          billingAmount={billingAmount}
          billingCurrency={billingCurrency}
          billingDueDate={billingDueDate}
          includePaymentLink={includePaymentLink}
          submitting={submitting}
          onBillingSubjectChange={onBillingSubjectChange}
          onBillingMessageChange={onBillingMessageChange}
          onBillingAmountChange={onBillingAmountChange}
          onBillingCurrencyChange={onBillingCurrencyChange}
          onBillingDueDateChange={onBillingDueDateChange}
          onIncludePaymentLinkChange={onIncludePaymentLinkChange}
          onSendBillingEmail={onSendBillingEmail}
        />
      )}

      {/* Email History - Only for non-team-members */}
      {!isTeamMember && billingEmails.length > 0 && (
        <BillingEmailHistory billingEmails={billingEmails} />
      )}
    </div>
  );
}

// Sub-components
function SubscriptionSection({ subscription }: { subscription: Subscription }) {
  return (
    <div className="p-6 bg-gradient-to-r from-green-50 to-blue-50 border border-green-200 rounded-lg">
      <h3 className="text-lg font-semibold text-brand-ink mb-4">
        Current Subscription
      </h3>
      <div className="space-y-3">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <p className="text-xs text-gray-600 uppercase">Plan</p>
            <p className="text-lg font-semibold text-brand-ink">
              {subscription.tierId || "Unknown"}
            </p>
          </div>
          <div>
            <p className="text-xs text-gray-600 uppercase">Status</p>
            <span
              className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                subscription.status === "active"
                  ? "bg-green-100 text-green-800"
                  : subscription.status === "trialing"
                    ? "bg-blue-100 text-blue-800"
                    : subscription.status === "past_due"
                      ? "bg-orange-100 text-orange-800"
                      : "bg-gray-100 text-gray-800"
              }`}
            >
              {subscription.status}
            </span>
          </div>
          <div>
            <p className="text-xs text-gray-600 uppercase">Billing Period</p>
            <p className="text-base font-medium">
              {subscription.billingPeriod || "monthly"}
            </p>
          </div>
          <div>
            <p className="text-xs text-gray-600 uppercase">Next Billing Date</p>
            <p className="text-base font-medium">
              {subscription.currentPeriodEnd
                ? new Date(subscription.currentPeriodEnd).toLocaleDateString()
                : "N/A"}
            </p>
          </div>
          {subscription.cardBrand && (
            <>
              <div>
                <p className="text-xs text-gray-600 uppercase">
                  Payment Method
                </p>
                <p className="text-base font-medium">
                  {subscription.cardBrand} **** {subscription.cardLastFour}
                </p>
              </div>
              <div>
                <p className="text-xs text-gray-600 uppercase">Last Payment</p>
                <p className="text-base font-medium">
                  {subscription.lastPaymentDate
                    ? new Date(
                        subscription.lastPaymentDate,
                      ).toLocaleDateString()
                    : "N/A"}
                </p>
              </div>
            </>
          )}
          {subscription.trialEndsAt && (
            <div className="col-span-2">
              <p className="text-xs text-gray-600 uppercase">Trial Ends</p>
              <p className="text-base font-medium">
                {new Date(subscription.trialEndsAt).toLocaleDateString()}
              </p>
            </div>
          )}
          {subscription.cancelAtPeriodEnd && (
            <div className="col-span-2 p-3 bg-yellow-100 border border-yellow-300 rounded">
              <p className="text-sm text-yellow-800">
                Subscription will cancel at period end
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function InvoiceHistorySection({
  invoices,
  invoiceSummary,
  loadingInvoices,
  showAllInvoices,
  onFetchInvoices,
  onShowAllInvoicesChange,
}: {
  invoices: StripeInvoice[];
  invoiceSummary: InvoiceSummary | null;
  loadingInvoices: boolean;
  showAllInvoices: boolean;
  onFetchInvoices: () => void;
  onShowAllInvoicesChange: (show: boolean) => void;
}) {
  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-brand-ink flex items-center gap-2">
          <Receipt className="w-5 h-5" />
          Invoice History
        </h3>
        <button
          onClick={onFetchInvoices}
          disabled={loadingInvoices}
          className="flex items-center gap-1 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 border rounded-lg hover:bg-gray-50"
        >
          <RefreshCw
            className={`w-4 h-4 ${loadingInvoices ? "animate-spin" : ""}`}
          />
          Refresh
        </button>
      </div>

      {/* Summary Stats */}
      {invoiceSummary && (
        <div className="grid grid-cols-4 gap-4 mb-4">
          <div className="p-3 bg-green-50 border border-green-200 rounded-lg text-center">
            <p className="text-2xl font-bold text-green-700">
              {String.fromCharCode(163)}
              {(invoiceSummary.totalPaid / 100).toFixed(2)}
            </p>
            <p className="text-xs text-green-600">Total Paid</p>
          </div>
          <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-center">
            <p className="text-2xl font-bold text-blue-700">
              {invoiceSummary.paidInvoices}
            </p>
            <p className="text-xs text-blue-600">Paid Invoices</p>
          </div>
          <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-center">
            <p className="text-2xl font-bold text-yellow-700">
              {invoiceSummary.openInvoices}
            </p>
            <p className="text-xs text-yellow-600">Open Invoices</p>
          </div>
          <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-center">
            <p className="text-2xl font-bold text-red-700">
              {invoiceSummary.failedPayments}
            </p>
            <p className="text-xs text-red-600">Failed Payments</p>
          </div>
        </div>
      )}

      {/* Invoice List */}
      {loadingInvoices ? (
        <div className="p-8 text-center text-gray-500">
          <RefreshCw className="w-8 h-8 animate-spin mx-auto mb-2" />
          Loading invoices...
        </div>
      ) : invoices.length === 0 ? (
        <div className="p-6 bg-gray-50 border border-gray-200 rounded-lg text-center">
          <Receipt className="w-8 h-8 text-gray-400 mx-auto mb-2" />
          <p className="text-sm text-gray-600">No invoices found</p>
        </div>
      ) : (
        <div className="space-y-2">
          {(showAllInvoices ? invoices : invoices.slice(0, 5)).map(
            (invoice) => (
              <InvoiceRow key={invoice.id} invoice={invoice} />
            ),
          )}

          {invoices.length > 5 && (
            <button
              onClick={() => onShowAllInvoicesChange(!showAllInvoices)}
              className="w-full flex items-center justify-center gap-2 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-200 rounded-lg hover:bg-gray-50"
            >
              {showAllInvoices ? (
                <>
                  <ChevronUp className="w-4 h-4" />
                  Show less
                </>
              ) : (
                <>
                  <ChevronDown className="w-4 h-4" />
                  Show all {invoices.length} invoices
                </>
              )}
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function InvoiceRow({ invoice }: { invoice: StripeInvoice }) {
  const getCurrencySymbol = (currency: string) => {
    if (currency === "GBP") return String.fromCharCode(163);
    if (currency === "USD") return "$";
    if (currency === "EUR") return String.fromCharCode(8364);
    return currency + " ";
  };

  return (
    <div className="flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100">
      <div className="flex-1">
        <div className="flex items-center gap-3">
          <span
            className={`px-2 py-1 text-xs font-medium rounded ${
              invoice.status === "paid"
                ? "bg-green-100 text-green-800"
                : invoice.status === "open"
                  ? "bg-yellow-100 text-yellow-800"
                  : invoice.status === "draft"
                    ? "bg-gray-100 text-gray-800"
                    : invoice.status === "void"
                      ? "bg-red-100 text-red-800"
                      : "bg-gray-100 text-gray-800"
            }`}
          >
            {invoice.status}
          </span>
          <span className="text-sm font-medium text-gray-900">
            {invoice.number || invoice.id.slice(0, 12)}
          </span>
        </div>
        <p className="text-sm text-gray-600 mt-1">{invoice.description}</p>
        <div className="flex items-center gap-4 mt-1 text-xs text-gray-500">
          <span>
            Created: {new Date(invoice.createdAt).toLocaleDateString()}
          </span>
          {invoice.paidAt && (
            <span className="text-green-600">
              Paid: {new Date(invoice.paidAt).toLocaleDateString()}
            </span>
          )}
        </div>
      </div>
      <div className="flex items-center gap-4">
        <div className="text-right">
          <p className="text-lg font-bold text-gray-900">
            {getCurrencySymbol(invoice.currency)}
            {(invoice.amount / 100).toFixed(2)}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {invoice.hostedInvoiceUrl && (
            <a
              href={invoice.hostedInvoiceUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="p-2 text-gray-500 hover:text-brand-green hover:bg-green-50 rounded"
              title="View Invoice"
            >
              <ExternalLink className="w-4 h-4" />
            </a>
          )}
          {invoice.invoicePdf && (
            <a
              href={invoice.invoicePdf}
              target="_blank"
              rel="noopener noreferrer"
              className="p-2 text-gray-500 hover:text-brand-green hover:bg-green-50 rounded"
              title="Download PDF"
            >
              <Download className="w-4 h-4" />
            </a>
          )}
        </div>
      </div>
    </div>
  );
}

function BillingEmailForm({
  billingSubject,
  billingMessage,
  billingAmount,
  billingCurrency,
  billingDueDate,
  includePaymentLink,
  submitting,
  onBillingSubjectChange,
  onBillingMessageChange,
  onBillingAmountChange,
  onBillingCurrencyChange,
  onBillingDueDateChange,
  onIncludePaymentLinkChange,
  onSendBillingEmail,
}: {
  billingSubject: string;
  billingMessage: string;
  billingAmount: string;
  billingCurrency: string;
  billingDueDate: string;
  includePaymentLink: boolean;
  submitting: boolean;
  onBillingSubjectChange: (value: string) => void;
  onBillingMessageChange: (value: string) => void;
  onBillingAmountChange: (value: string) => void;
  onBillingCurrencyChange: (value: string) => void;
  onBillingDueDateChange: (value: string) => void;
  onIncludePaymentLinkChange: (value: boolean) => void;
  onSendBillingEmail: () => void;
}) {
  const isDisabled =
    submitting ||
    !billingSubject.trim() ||
    !billingMessage.trim() ||
    (includePaymentLink && (!billingAmount || parseFloat(billingAmount) <= 0));

  return (
    <div className="border border-gray-200 rounded-lg p-6">
      <h3 className="text-lg font-semibold text-brand-ink mb-4 flex items-center gap-2">
        <Mail className="w-5 h-5" />
        Send Billing Email
      </h3>
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Subject *
          </label>
          <input
            type="text"
            value={billingSubject}
            onChange={(e) => onBillingSubjectChange(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="Invoice for December 2025"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Message *
          </label>
          <textarea
            value={billingMessage}
            onChange={(e) => onBillingMessageChange(e.target.value)}
            rows={4}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="Dear customer, please find your invoice attached..."
          />
        </div>

        <div className="grid grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <DollarSign className="w-4 h-4 inline mr-1" />
              Amount {includePaymentLink && "*"}
            </label>
            <input
              type="number"
              value={billingAmount}
              onChange={(e) => onBillingAmountChange(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
              placeholder="99.99"
              min="0"
              step="0.01"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Currency
            </label>
            <select
              value={billingCurrency}
              onChange={(e) => onBillingCurrencyChange(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            >
              {CURRENCY_OPTIONS.map((curr) => (
                <option key={curr.value} value={curr.value}>
                  {curr.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              <Calendar className="w-4 h-4 inline mr-1" />
              Due Date
            </label>
            <input
              type="date"
              value={billingDueDate}
              onChange={(e) => onBillingDueDateChange(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
              min={new Date().toISOString().split("T")[0]}
            />
          </div>
        </div>

        <div className="flex items-center gap-3 p-4 bg-green-50 border border-green-200 rounded-lg">
          <input
            type="checkbox"
            id="includePaymentLink"
            checked={includePaymentLink}
            onChange={(e) => onIncludePaymentLinkChange(e.target.checked)}
            className="w-5 h-5 text-brand-green rounded focus:ring-brand-green"
          />
          <label htmlFor="includePaymentLink" className="flex-1">
            <span className="font-medium text-gray-900">
              Include Payment Link
            </span>
            <p className="text-sm text-gray-600">
              Generate a secure Stripe checkout link for the user to pay
              directly via the email
            </p>
          </label>
          <CreditCard className="w-6 h-6 text-green-600" />
        </div>

        <button
          onClick={onSendBillingEmail}
          disabled={isDisabled}
          className="flex items-center justify-center gap-2 w-full px-4 py-3 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium"
        >
          {submitting ? (
            <>
              <RefreshCw className="w-4 h-4 animate-spin" />
              Sending...
            </>
          ) : (
            <>
              <Mail className="w-4 h-4" />
              {includePaymentLink
                ? "Send Email with Payment Link"
                : "Send Billing Email"}
            </>
          )}
        </button>
      </div>
    </div>
  );
}

function BillingEmailHistory({
  billingEmails,
}: {
  billingEmails: BillingEmail[];
}) {
  return (
    <div>
      <h3 className="text-lg font-semibold text-brand-ink mb-4">
        Recent Billing Emails
      </h3>
      <div className="space-y-2">
        {billingEmails.slice(0, 10).map((email) => (
          <div
            key={email.id}
            className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
          >
            <div>
              <p className="text-sm font-medium text-gray-900">
                {email.subject}
              </p>
              <p className="text-xs text-gray-500 mt-1">
                {new Date(email.sentAt).toLocaleString()}
                {email.amount && (
                  <span className="ml-2 text-green-600 font-medium">
                    {String.fromCharCode(163)}
                    {email.amount.toFixed(2)}
                  </span>
                )}
              </p>
            </div>
            <span
              className={`px-2 py-1 text-xs font-medium rounded ${
                email.status === "sent"
                  ? "bg-green-100 text-green-800"
                  : email.status === "paid"
                    ? "bg-blue-100 text-blue-800"
                    : email.status === "overdue"
                      ? "bg-orange-100 text-orange-800"
                      : "bg-red-100 text-red-800"
              }`}
            >
              {email.status}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}
