"use client";

import { 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";

export function SimCallHistoryContainer() {
  const params = useParams();
  const subscriptionId = params["id"] as string;

  const [activeTab, setActiveTab] = useState<TabType>("domestic");
  // Use September 2025 as the current month (latest available - 2 months behind)
  const currentMonth = "2025-09";
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Data states
  const [domesticData, setDomesticData] = useState<SimDomesticCallHistoryResponse | null>(null);
  const [internationalData, setInternationalData] =
    useState<SimInternationalCallHistoryResponse | null>(null);
  const [smsData, setSmsData] = useState<SimSmsHistoryResponse | null>(null);

  // Pagination states
  const [domesticPage, setDomesticPage] = useState(1);
  const [internationalPage, setInternationalPage] = useState(1);
  const [smsPage, setSmsPage] = useState(1);

  // Fetch data when tab changes
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);

      try {
        if (activeTab === "domestic") {
          const data = await simActionsService.getDomesticCallHistory(
            subscriptionId,
            currentMonth,
            domesticPage,
            50
          );
          setDomesticData(data);
        } else if (activeTab === "international") {
          const data = await simActionsService.getInternationalCallHistory(
            subscriptionId,
            currentMonth,
            internationalPage,
            50
          );
          setInternationalData(data);
        } else if (activeTab === "sms") {
          const data = await simActionsService.getSmsHistory(
            subscriptionId,
            currentMonth,
            smsPage,
            50
          );
          setSmsData(data);
        }
      } catch (e: unknown) {
        setError(
          process.env.NODE_ENV === "development"
            ? e instanceof Error
              ? e.message
              : "Failed to load history"
            : "Unable to load your history right now. Please try again."
        );
      } finally {
        setLoading(false);
      }
    };

    void fetchData();
  }, [subscriptionId, activeTab, domesticPage, internationalPage, smsPage]);

  // Reset page when tab changes
  useEffect(() => {
    if (activeTab === "domestic") setDomesticPage(1);
    if (activeTab === "international") setInternationalPage(1);
    if (activeTab === "sms") setSmsPage(1);
  }, [activeTab]);

  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>
          {/* Current Month Display */}
          <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>

          {/* Tabs */}
          <div className="border-b border-border mb-6">
            <nav className="flex -mb-px space-x-8">
              <button
                onClick={() => setActiveTab("domestic")}
                className={`flex items-center gap-2 py-4 px-1 border-b-2 text-sm font-medium transition-colors ${
                  activeTab === "domestic"
                    ? "border-primary text-primary"
                    : "border-transparent text-muted-foreground hover:text-foreground hover:border-border"
                }`}
              >
                <PhoneIcon className="h-5 w-5" />
                Domestic Calls
                {domesticData && (
                  <span className="ml-1 text-xs text-muted-foreground/70">
                    ({domesticData.pagination.total})
                  </span>
                )}
              </button>
              <button
                onClick={() => setActiveTab("international")}
                className={`flex items-center gap-2 py-4 px-1 border-b-2 text-sm font-medium transition-colors ${
                  activeTab === "international"
                    ? "border-primary text-primary"
                    : "border-transparent text-muted-foreground hover:text-foreground hover:border-border"
                }`}
              >
                <GlobeAltIcon className="h-5 w-5" />
                International Calls
                {internationalData && (
                  <span className="ml-1 text-xs text-muted-foreground/70">
                    ({internationalData.pagination.total})
                  </span>
                )}
              </button>
              <button
                onClick={() => setActiveTab("sms")}
                className={`flex items-center gap-2 py-4 px-1 border-b-2 text-sm font-medium transition-colors ${
                  activeTab === "sms"
                    ? "border-primary text-primary"
                    : "border-transparent text-muted-foreground hover:text-foreground hover:border-border"
                }`}
              >
                <ChatBubbleLeftIcon className="h-5 w-5" />
                SMS History
                {smsData && (
                  <span className="ml-1 text-xs text-muted-foreground/70">
                    ({smsData.pagination.total})
                  </span>
                )}
              </button>
            </nav>
          </div>

          {/* Error */}
          {error && (
            <div className="mb-4">
              <AlertBanner variant="error" title="Error">
                {error}
              </AlertBanner>
            </div>
          )}

          {/* Loading */}
          {loading && (
            <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>
          )}

          {/* Domestic Calls Table */}
          {!loading && activeTab === "domestic" && domesticData && (
            <>
              {domesticData.calls.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  No domestic calls found for this month
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-border">
                    <thead className="bg-muted/50">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Date
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Time
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Called To
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Call Length
                        </th>
                        <th className="px-4 py-3 text-right text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Call Charge (¥)
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-card divide-y divide-border">
                      {domesticData.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>
              )}
              {domesticData.pagination.total > 0 && (
                <PaginationBar
                  currentPage={domesticData.pagination.page}
                  pageSize={domesticData.pagination.limit}
                  totalItems={domesticData.pagination.total}
                  onPageChange={setDomesticPage}
                  className="mt-4"
                />
              )}
            </>
          )}

          {/* International Calls Table */}
          {!loading && activeTab === "international" && internationalData && (
            <>
              {internationalData.calls.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  No international calls found for this month
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-border">
                    <thead className="bg-muted/50">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Date
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Start Time
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Stop Time
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Country
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Called To
                        </th>
                        <th className="px-4 py-3 text-right text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Call Charge (¥)
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-card divide-y divide-border">
                      {internationalData.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>
              )}
              {internationalData.pagination.total > 0 && (
                <PaginationBar
                  currentPage={internationalData.pagination.page}
                  pageSize={internationalData.pagination.limit}
                  totalItems={internationalData.pagination.total}
                  onPageChange={setInternationalPage}
                  className="mt-4"
                />
              )}
            </>
          )}

          {/* SMS Table */}
          {!loading && activeTab === "sms" && smsData && (
            <>
              {smsData.messages.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  No SMS found for this month
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-border">
                    <thead className="bg-muted/50">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Date
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Time
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Sent To
                        </th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                          Type
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-card divide-y divide-border">
                      {smsData.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">
                            <span
                              className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${
                                msg.type === "International SMS"
                                  ? "bg-accent-soft text-accent-foreground"
                                  : "bg-info-soft text-info"
                              }`}
                            >
                              {msg.type}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
              {smsData.pagination.total > 0 && (
                <PaginationBar
                  currentPage={smsData.pagination.page}
                  pageSize={smsData.pagination.limit}
                  totalItems={smsData.pagination.total}
                  onPageChange={setSmsPage}
                  className="mt-4"
                />
              )}
            </>
          )}

          {/* Info Note */}
          <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>
        </SubCard>
      </div>
    </PageLayout>
  );
}

export default SimCallHistoryContainer;
