/**
 * Billing Management Page
 *
 * Redesigned billing management with master-detail layout.
 * Uses the commerce.billing system with versioning for grandfathering support.
 *
 * Current Entities & Endpoints:
 * - Plans: /billing/admin/plans/ (CRUD)
 * - PlanVersions: /billing/admin/plan-versions/ (CRUD, grandfathering)
 * - Features: /billing/admin/features/ (CRUD)
 * - AddOns: /billing/admin/addons/ (CRUD)
 * - Entitlements: /me/entitlements/ (read only)
 *
 * Layout:
 * - Top tabs: Catalog | Overrides | Invoices
 * - Catalog tab has master-detail: left sidebar + main panel
 */

import React, { useState, useMemo } from 'react';
import { CreditCard, Package, Shield, FileText, Loader2 } from 'lucide-react';
import {
  usePlans,
  useAddOnProducts,
  type PlanWithVersions,
  type PlanVersion,
  type AddOnProduct,
} from '../../hooks/useBillingAdmin';
import {
  CatalogListPanel,
  PlanDetailPanel,
  PlanEditorWizard,
  AddOnEditorModal,
  type CatalogItem,
} from '../../billing';
import { ErrorMessage, Alert } from '../../components/ui';

// Tab types
type MainTab = 'catalog' | 'overrides' | 'invoices';

const BillingManagement: React.FC = () => {
  const [activeTab, setActiveTab] = useState<MainTab>('catalog');
  const [selectedItem, setSelectedItem] = useState<CatalogItem | null>(null);
  const [showPlanWizard, setShowPlanWizard] = useState(false);
  const [showAddonModal, setShowAddonModal] = useState(false);
  const [editingPlan, setEditingPlan] = useState<PlanWithVersions | null>(null);
  const [editingVersion, setEditingVersion] = useState<PlanVersion | null>(null);
  const [editingAddon, setEditingAddon] = useState<AddOnProduct | null>(null);

  // Fetch data
  const { data: plans, isLoading: plansLoading, error: plansError } = usePlans();
  const { data: addons, isLoading: addonsLoading, error: addonsError } = useAddOnProducts();

  const isLoading = plansLoading || addonsLoading;
  const error = plansError || addonsError;

  // Convert plans and addons to catalog items
  const catalogItems: CatalogItem[] = useMemo(() => {
    const items: CatalogItem[] = [];

    // Add plans
    plans?.forEach((plan) => {
      const activeVersion = plan.active_version;
      items.push({
        id: plan.id,
        type: 'plan',
        code: plan.code,
        name: plan.name,
        isActive: plan.is_active,
        isPublic: activeVersion?.is_public ?? false,
        isLegacy: activeVersion?.is_legacy ?? false,
        priceMonthly: activeVersion?.price_monthly_cents,
        priceYearly: activeVersion?.price_yearly_cents,
        subscriberCount: plan.total_subscribers,
        stripeProductId: activeVersion?.stripe_product_id,
      });
    });

    // Add addons
    addons?.forEach((addon) => {
      items.push({
        id: addon.id,
        type: 'addon',
        code: addon.code,
        name: addon.name,
        isActive: addon.is_active,
        isPublic: true,
        isLegacy: false,
        priceMonthly: addon.price_monthly_cents,
        stripeProductId: addon.stripe_product_id,
      });
    });

    return items;
  }, [plans, addons]);

  // Find selected plan or addon
  const selectedPlan = useMemo(() => {
    if (!selectedItem || selectedItem.type !== 'plan') return null;
    return plans?.find((p) => p.id === selectedItem.id) || null;
  }, [selectedItem, plans]);

  const selectedAddon = useMemo(() => {
    if (!selectedItem || selectedItem.type !== 'addon') return null;
    return addons?.find((a) => a.id === selectedItem.id) || null;
  }, [selectedItem, addons]);

  // Handlers
  const handleCreatePlan = () => {
    setEditingPlan(null);
    setEditingVersion(null);
    setShowPlanWizard(true);
  };

  const handleCreateAddon = () => {
    setEditingAddon(null);
    setShowAddonModal(true);
  };

  const handleEditAddon = () => {
    if (selectedAddon) {
      setEditingAddon(selectedAddon);
      setShowAddonModal(true);
    }
  };

  const handleCloseAddonModal = () => {
    setShowAddonModal(false);
    setEditingAddon(null);
  };

  const handleEditPlan = () => {
    if (selectedPlan) {
      setEditingPlan(selectedPlan);
      setEditingVersion(selectedPlan.active_version);
      setShowPlanWizard(true);
    }
  };

  const handleDuplicatePlan = () => {
    if (selectedPlan) {
      // Open wizard with plan data but clear IDs
      setEditingPlan(null);
      // TODO: Pre-fill wizard with selected plan's data
      setShowPlanWizard(true);
    }
  };

  const handleCreateVersion = () => {
    if (selectedPlan) {
      setEditingPlan(selectedPlan);
      setEditingVersion(null); // null = create new version
      setShowPlanWizard(true);
    }
  };

  const handleEditVersion = (version: PlanVersion) => {
    if (selectedPlan) {
      setEditingPlan(selectedPlan);
      setEditingVersion(version);
      setShowPlanWizard(true);
    }
  };

  const handleCloseWizard = () => {
    setShowPlanWizard(false);
    setEditingPlan(null);
    setEditingVersion(null);
  };

  const tabs = [
    { id: 'catalog' as const, label: 'Catalog', icon: Package },
    { id: 'overrides' as const, label: 'Overrides', icon: Shield },
    { id: 'invoices' as const, label: 'Invoices', icon: FileText },
  ];

  return (
    <div className="h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
      {/* Page Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
              <CreditCard className="w-6 h-6 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-gray-900 dark:text-white">
                Billing Management
              </h1>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                Manage subscription plans, features, and add-ons
              </p>
            </div>
          </div>
        </div>

        {/* Main Tabs */}
        <div className="flex gap-1 mt-4">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${
                  isActive
                    ? 'bg-gray-50 dark:bg-gray-900 text-blue-600 dark:text-blue-400 border-t border-l border-r border-gray-200 dark:border-gray-700'
                    : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
                }`}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      {/* Tab Content */}
      <div className="flex-1 overflow-hidden">
        {/* Catalog Tab */}
        {activeTab === 'catalog' && (
          <div className="h-full flex">
            {/* Left Sidebar */}
            <div className="w-96 flex-shrink-0">
              {isLoading ? (
                <div className="flex items-center justify-center h-full">
                  <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
                </div>
              ) : error ? (
                <div className="p-4">
                  <ErrorMessage message="Failed to load billing data" />
                </div>
              ) : (
                <CatalogListPanel
                  items={catalogItems}
                  selectedId={selectedItem?.id || null}
                  onSelect={setSelectedItem}
                  onCreatePlan={handleCreatePlan}
                  onCreateAddon={handleCreateAddon}
                />
              )}
            </div>

            {/* Main Panel */}
            <div className="flex-1 flex flex-col overflow-hidden bg-white dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700">
              <PlanDetailPanel
                plan={selectedPlan}
                addon={selectedAddon}
                onEdit={selectedAddon ? handleEditAddon : handleEditPlan}
                onDuplicate={handleDuplicatePlan}
                onCreateVersion={handleCreateVersion}
                onEditVersion={handleEditVersion}
              />
            </div>
          </div>
        )}

        {/* Overrides Tab */}
        {activeTab === 'overrides' && (
          <div className="p-6">
            <Alert
              variant="info"
              message={
                <>
                  <strong>Entitlement Overrides</strong>
                  <p className="mt-1">
                    Overrides allow you to grant or revoke specific features for individual tenants.
                    Resolution order: Override &gt; Add-on &gt; Plan
                  </p>
                </>
              }
            />
            <div className="mt-6 text-center text-gray-500 dark:text-gray-400 py-12">
              <Shield className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>Overrides management coming soon</p>
              <p className="text-sm mt-1">
                Use Django admin at /admin/billing/entitlementoverride/ for now
              </p>
            </div>
          </div>
        )}

        {/* Invoices Tab */}
        {activeTab === 'invoices' && (
          <div className="p-6">
            <Alert
              variant="info"
              message={
                <>
                  <strong>Invoice Management</strong>
                  <p className="mt-1">
                    View and manage billing invoices for all tenants.
                  </p>
                </>
              }
            />
            <div className="mt-6 text-center text-gray-500 dark:text-gray-400 py-12">
              <FileText className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>Invoice listing coming soon</p>
              <p className="text-sm mt-1">
                Use Django admin at /admin/billing/invoice/ for now
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Plan Editor Wizard */}
      {showPlanWizard && (
        <PlanEditorWizard
          isOpen={showPlanWizard}
          onClose={handleCloseWizard}
          mode={editingPlan ? 'edit' : 'create'}
          initialData={
            editingPlan
              ? {
                  id: editingPlan.id,
                  code: editingPlan.code,
                  name: editingPlan.name,
                  description: editingPlan.description,
                  display_order: editingPlan.display_order,
                  is_active: editingPlan.is_active,
                  version: editingVersion
                    ? {
                        id: editingVersion.id,
                        name: editingVersion.name,
                        price_monthly_cents: editingVersion.price_monthly_cents,
                        price_yearly_cents: editingVersion.price_yearly_cents,
                        transaction_fee_percent: editingVersion.transaction_fee_percent,
                        transaction_fee_fixed_cents: editingVersion.transaction_fee_fixed_cents,
                        trial_days: editingVersion.trial_days,
                        is_public: editingVersion.is_public,
                        is_most_popular: editingVersion.is_most_popular,
                        show_price: editingVersion.show_price,
                        marketing_features: editingVersion.marketing_features,
                        stripe_product_id: editingVersion.stripe_product_id,
                        stripe_price_id_monthly: editingVersion.stripe_price_id_monthly,
                        stripe_price_id_yearly: editingVersion.stripe_price_id_yearly,
                        features: editingVersion.features,
                        subscriber_count: editingVersion.subscriber_count,
                      }
                    : undefined,
                }
              : undefined
          }
        />
      )}

      {/* Add-On Editor Modal */}
      {showAddonModal && (
        <AddOnEditorModal
          isOpen={showAddonModal}
          onClose={handleCloseAddonModal}
          addon={editingAddon}
        />
      )}
    </div>
  );
};

export default BillingManagement;
