"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { PageLayout } from "@/components/templates/PageLayout";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { PhoneIcon, GlobeAltIcon, ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
import { simActionsService } from "@/features/subscriptions/api/sim-actions.api";
import type {
  SimDomesticCallHistoryResponse,
  SimInternationalCallHistoryResponse,
  SimSmsHistoryResponse,
} from "@customer-portal/domain/sim";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Formatting } from "@customer-portal/domain/toolkit";
import { PaginationBar } from "@/components/molecules/PaginationBar/PaginationBar";

const { formatCurrency } = Formatting;

type TabType = "domestic" | "international" | "sms";

// CSS class constants for tab styling
const TAB_ACTIVE_CLASSES = "border-primary text-primary";
const TAB_INACTIVE_CLASSES =
  "border-transparent text-muted-foreground hover:text-foreground hover:border-border";

// Table header cell class
const TABLE_HEADER_CELL =
  "px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider";
const TABLE_HEADER_CELL_RIGHT =
  "px-4 py-3 text-right text-xs font-medium text-muted-foreground uppercase tracking-wider";

const CURRENT_MONTH = "2025-09";

function useCallHistoryData(subscriptionId: string) {
  const [activeTab, setActiveTab] = useState<TabType>("domestic");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [domesticData, setDomesticData] = useState<SimDomesticCallHistoryResponse | null>(null);
  const [internationalData, setInternationalData] =
    useState<SimInternationalCallHistoryResponse | null>(null);
  const [smsData, setSmsData] = useState<SimSmsHistoryResponse | null>(null);
  const [domesticPage, setDomesticPage] = useState(1);
  const [internationalPage, setInternationalPage] = useState(1);
  const [smsPage, setSmsPage] = useState(1);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        switch (activeTab) {
          case "domestic":
            setDomesticData(
              await simActionsService.getDomesticCallHistory(
                subscriptionId,
                CURRENT_MONTH,
                domesticPage,
                50
              )
            );
            break;
          case "international":
            setInternationalData(
              await simActionsService.getInternationalCallHistory(
                subscriptionId,
                CURRENT_MONTH,
                internationalPage,
                50
              )
            );
            break;
          case "sms":
            setSmsData(
              await simActionsService.getSmsHistory(subscriptionId, CURRENT_MONTH, smsPage, 50)
            );
            break;
        }
      } catch (e: unknown) {
        const devMessage = e instanceof Error ? e.message : "Failed to load history";
        setError(
          process.env.NODE_ENV === "development"
            ? devMessage
            : "Unable to load your history right now. Please try again."
        );
      } finally {
        setLoading(false);
      }
    };
    void fetchData();
  }, [subscriptionId, activeTab, domesticPage, internationalPage, smsPage]);

  useEffect(() => {
    switch (activeTab) {
      case "domestic":
        setDomesticPage(1);
        break;
      case "international":
        setInternationalPage(1);
        break;
      case "sms":
        setSmsPage(1);
        break;
    }
  }, [activeTab]);

  return {
    activeTab,
    setActiveTab,
    loading,
    error,
    domesticData,
    internationalData,
    smsData,
    setDomesticPage,
    setInternationalPage,
    setSmsPage,
  };
}

export function SimCallHistoryContainer(): React.ReactElement {
  const params = useParams();
  const subscriptionId = params["id"] as string;
  const state = useCallHistoryData(subscriptionId);

  return (
    <PageLayout
      icon={<PhoneIcon />}
      title="Call & SMS History"
      description="View your call and SMS records"
    >
      <div className="max-w-5xl mx-auto">
        <div className="mb-4">
          <Link
            href={`/account/subscriptions/${subscriptionId}#sim-management`}
            className="text-primary hover:underline"
          >
            Back to SIM Management
          </Link>
        </div>
        <SubCard>
          <MonthDisplayBanner />
          <HistoryTabs
            activeTab={state.activeTab}
            setActiveTab={state.setActiveTab}
            domesticData={state.domesticData}
            internationalData={state.internationalData}
            smsData={state.smsData}
          />
          {state.error && (
            <div className="mb-4">
              <AlertBanner variant="error" title="Error">
                {state.error}
              </AlertBanner>
            </div>
          )}
          {state.loading && <LoadingSkeleton />}
          <HistoryTableContent
            loading={state.loading}
            activeTab={state.activeTab}
            domesticData={state.domesticData}
            internationalData={state.internationalData}
            smsData={state.smsData}
            setDomesticPage={state.setDomesticPage}
            setInternationalPage={state.setInternationalPage}
            setSmsPage={state.setSmsPage}
          />
          <ImportantNotesSection />
        </SubCard>
      </div>
    </PageLayout>
  );
}

interface HistoryTableContentProps {
  loading: boolean;
  activeTab: TabType;
  domesticData: SimDomesticCallHistoryResponse | null;
  internationalData: SimInternationalCallHistoryResponse | null;
  smsData: SimSmsHistoryResponse | null;
  setDomesticPage: (page: number) => void;
  setInternationalPage: (page: number) => void;
  setSmsPage: (page: number) => void;
}

function HistoryTableContent({
  loading,
  activeTab,
  domesticData,
  internationalData,
  smsData,
  setDomesticPage,
  setInternationalPage,
  setSmsPage,
}: HistoryTableContentProps): React.ReactElement | null {
  if (loading) return null;
  if (activeTab === "domestic" && domesticData) {
    return <DomesticCallsTable data={domesticData} onPageChange={setDomesticPage} />;
  }
  if (activeTab === "international" && internationalData) {
    return <InternationalCallsTable data={internationalData} onPageChange={setInternationalPage} />;
  }
  if (activeTab === "sms" && smsData) {
    return <SmsHistoryTable data={smsData} onPageChange={setSmsPage} />;
  }
  return null;
}

// ============================================================================
// Sub-Components
// ============================================================================

function MonthDisplayBanner(): React.ReactElement {
  return (
    <div className="mb-6 p-4 bg-info-soft border border-info/25 rounded-lg">
      <div className="flex items-center gap-2">
        <span className="text-sm font-medium text-foreground">
          Showing data for: September 2025
        </span>
      </div>
      <p className="text-xs text-muted-foreground mt-1">
        Call/SMS history is available approximately 2 months after the calls are made.
      </p>
    </div>
  );
}

interface HistoryTabsProps {
  activeTab: TabType;
  setActiveTab: (tab: TabType) => void;
  domesticData: SimDomesticCallHistoryResponse | null;
  internationalData: SimInternationalCallHistoryResponse | null;
  smsData: SimSmsHistoryResponse | null;
}

function HistoryTabs({
  activeTab,
  setActiveTab,
  domesticData,
  internationalData,
  smsData,
}: HistoryTabsProps): React.ReactElement {
  const domesticCount = domesticData?.pagination.total;
  const internationalCount = internationalData?.pagination.total;
  const smsCount = smsData?.pagination.total;

  return (
    <div className="border-b border-border mb-6">
      <nav className="flex -mb-px space-x-8">
        <TabButton
          active={activeTab === "domestic"}
          onClick={() => setActiveTab("domestic")}
          icon={<PhoneIcon className="h-5 w-5" />}
          label="Domestic Calls"
          {...(domesticCount !== undefined && { count: domesticCount })}
        />
        <TabButton
          active={activeTab === "international"}
          onClick={() => setActiveTab("international")}
          icon={<GlobeAltIcon className="h-5 w-5" />}
          label="International Calls"
          {...(internationalCount !== undefined && { count: internationalCount })}
        />
        <TabButton
          active={activeTab === "sms"}
          onClick={() => setActiveTab("sms")}
          icon={<ChatBubbleLeftIcon className="h-5 w-5" />}
          label="SMS History"
          {...(smsCount !== undefined && { count: smsCount })}
        />
      </nav>
    </div>
  );
}

interface TabButtonProps {
  active: boolean;
  onClick: () => void;
  icon: React.ReactNode;
  label: string;
  count?: number;
}

function TabButton({ active, onClick, icon, label, count }: TabButtonProps): React.ReactElement {
  const tabClasses = active ? TAB_ACTIVE_CLASSES : TAB_INACTIVE_CLASSES;
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-2 py-4 px-1 border-b-2 text-sm font-medium transition-colors ${tabClasses}`}
    >
      {icon}
      {label}
      {count !== undefined && (
        <span className="ml-1 text-xs text-muted-foreground/70">({count})</span>
      )}
    </button>
  );
}

function LoadingSkeleton(): React.ReactElement {
  return (
    <div className="animate-pulse space-y-2">
      {[1, 2, 3, 4, 5].map(i => (
        <div key={i} className="h-12 bg-muted rounded"></div>
      ))}
    </div>
  );
}

interface DomesticCallsTableProps {
  data: SimDomesticCallHistoryResponse;
  onPageChange: (page: number) => void;
}

function DomesticCallsTable({ data, onPageChange }: DomesticCallsTableProps): React.ReactElement {
  if (data.calls.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        No domestic calls found for this month
      </div>
    );
  }

  return (
    <>
      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-border">
          <thead className="bg-muted/50">
            <tr>
              <th className={TABLE_HEADER_CELL}>Date</th>
              <th className={TABLE_HEADER_CELL}>Time</th>
              <th className={TABLE_HEADER_CELL}>Called To</th>
              <th className={TABLE_HEADER_CELL}>Call Length</th>
              <th className={TABLE_HEADER_CELL_RIGHT}>Call Charge (¥)</th>
            </tr>
          </thead>
          <tbody className="bg-card divide-y divide-border">
            {data.calls.map(call => (
              <tr key={call.id} className="hover:bg-muted/30 transition-colors">
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground">{call.date}</td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-muted-foreground">
                  {call.time}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground font-mono">
                  {call.calledTo}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-muted-foreground">
                  {call.callLength}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground text-right font-medium">
                  {formatCurrency(call.callCharge)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {data.pagination.total > 0 && (
        <PaginationBar
          currentPage={data.pagination.page}
          pageSize={data.pagination.limit}
          totalItems={data.pagination.total}
          onPageChange={onPageChange}
          className="mt-4"
        />
      )}
    </>
  );
}

interface InternationalCallsTableProps {
  data: SimInternationalCallHistoryResponse;
  onPageChange: (page: number) => void;
}

function InternationalCallsTable({
  data,
  onPageChange,
}: InternationalCallsTableProps): React.ReactElement {
  if (data.calls.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        No international calls found for this month
      </div>
    );
  }

  return (
    <>
      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-border">
          <thead className="bg-muted/50">
            <tr>
              <th className={TABLE_HEADER_CELL}>Date</th>
              <th className={TABLE_HEADER_CELL}>Start Time</th>
              <th className={TABLE_HEADER_CELL}>Stop Time</th>
              <th className={TABLE_HEADER_CELL}>Country</th>
              <th className={TABLE_HEADER_CELL}>Called To</th>
              <th className={TABLE_HEADER_CELL_RIGHT}>Call Charge (¥)</th>
            </tr>
          </thead>
          <tbody className="bg-card divide-y divide-border">
            {data.calls.map(call => (
              <tr key={call.id} className="hover:bg-muted/30 transition-colors">
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground">{call.date}</td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-muted-foreground">
                  {call.startTime}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-muted-foreground">
                  {call.stopTime || "—"}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground">
                  {call.country || "—"}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground font-mono">
                  {call.calledTo}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground text-right font-medium">
                  {formatCurrency(call.callCharge)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {data.pagination.total > 0 && (
        <PaginationBar
          currentPage={data.pagination.page}
          pageSize={data.pagination.limit}
          totalItems={data.pagination.total}
          onPageChange={onPageChange}
          className="mt-4"
        />
      )}
    </>
  );
}

interface SmsHistoryTableProps {
  data: SimSmsHistoryResponse;
  onPageChange: (page: number) => void;
}

function SmsHistoryTable({ data, onPageChange }: SmsHistoryTableProps): React.ReactElement {
  if (data.messages.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground">No SMS found for this month</div>
    );
  }

  return (
    <>
      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-border">
          <thead className="bg-muted/50">
            <tr>
              <th className={TABLE_HEADER_CELL}>Date</th>
              <th className={TABLE_HEADER_CELL}>Time</th>
              <th className={TABLE_HEADER_CELL}>Sent To</th>
              <th className={TABLE_HEADER_CELL}>Type</th>
            </tr>
          </thead>
          <tbody className="bg-card divide-y divide-border">
            {data.messages.map(msg => (
              <tr key={msg.id} className="hover:bg-muted/30 transition-colors">
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground">{msg.date}</td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-muted-foreground">
                  {msg.time}
                </td>
                <td className="px-4 py-3 whitespace-nowrap text-sm text-foreground font-mono">
                  {msg.sentTo}
                </td>
                <td className="px-4 py-3 whitespace-nowrap">
                  <SmsTypeBadge type={msg.type} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {data.pagination.total > 0 && (
        <PaginationBar
          currentPage={data.pagination.page}
          pageSize={data.pagination.limit}
          totalItems={data.pagination.total}
          onPageChange={onPageChange}
          className="mt-4"
        />
      )}
    </>
  );
}

function SmsTypeBadge({ type }: { type: string }): React.ReactElement {
  const badgeClasses =
    type === "International SMS"
      ? "bg-accent-soft text-accent-foreground"
      : "bg-info-soft text-info";

  return (
    <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${badgeClasses}`}>
      {type}
    </span>
  );
}

function ImportantNotesSection(): React.ReactElement {
  return (
    <div className="mt-6 p-4 bg-muted border border-border rounded-lg">
      <h4 className="text-sm font-medium text-foreground mb-2">Important Notes</h4>
      <ul className="text-sm text-muted-foreground space-y-1">
        <li>
          Call/SMS history is updated approximately 2 months after the calls/messages are made
        </li>
        <li>The history shows approximately 3 months of records</li>
        <li>Call charges shown are based on the carrier billing data</li>
      </ul>
    </div>
  );
}

export default SimCallHistoryContainer;
