"use client";

import { forwardRef } from "react";
import {
  ServerIcon,
  CalendarIcon,
  CurrencyYenIcon,
  IdentificationIcon,
  TagIcon,
} from "@heroicons/react/24/outline";
import { StatusPill } from "@/components/atoms/status-pill";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import type { Subscription } from "@customer-portal/domain/subscriptions";

import { useFormatCurrency } from "@/shared/hooks";
import { cn, formatIsoDate } from "@/shared/utils";
import {
  getBillingCycleLabel,
  getSubscriptionStatusIcon,
  getSubscriptionStatusVariant,
} from "@/features/subscriptions/utils/status-presenters";

interface SubscriptionDetailsProps {
  subscription: Subscription;
  showServiceSpecificSections?: boolean;
  className?: string;
}

const isSimService = (productName: string) => {
  return productName.toLowerCase().includes("sim");
};

const isInternetService = (productName: string) => {
  const name = productName.toLowerCase();
  return name.includes("internet") || name.includes("broadband") || name.includes("fiber");
};

const isVpnService = (productName: string) => {
  return productName.toLowerCase().includes("vpn");
};

interface ServiceInfoCardProps {
  title: string;
  heading: string;
  description: string;
  features: string[];
  colorScheme: "info" | "success";
}

function ServiceInfoCard({
  title,
  heading,
  description,
  features,
  colorScheme,
}: ServiceInfoCardProps) {
  const bgClass =
    colorScheme === "info"
      ? "bg-info-bg border-info-border"
      : "bg-success-bg border-success-border";
  const iconBgClass = colorScheme === "info" ? "bg-info/20" : "bg-success/20";
  const iconTextClass = colorScheme === "info" ? "text-info" : "text-success";
  const headingClass = colorScheme === "info" ? "text-info" : "text-success";
  const textClass = colorScheme === "info" ? "text-info/80" : "text-success/80";
  const listClass = colorScheme === "info" ? "text-info/70" : "text-success/70";

  return (
    <SubCard title={title} icon={<ServerIcon className="h-5 w-5" />}>
      <div className={`${bgClass} border rounded-lg p-4`}>
        <div className="flex items-start space-x-3">
          <div className={`${iconBgClass} rounded-lg p-2`}>
            <ServerIcon className={`h-5 w-5 ${iconTextClass}`} />
          </div>
          <div>
            <h4 className={`text-sm font-semibold ${headingClass} mb-2`}>{heading}</h4>
            <p className={`text-sm ${textClass} mb-3`}>{description}</p>
            <ul className={`text-sm ${listClass} space-y-1`}>
              {features.map(feature => (
                <li key={feature}>• {feature}</li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </SubCard>
  );
}

function MainDetailsCard({
  subscription,
  formatCurrency,
}: {
  subscription: Subscription;
  formatCurrency: ReturnType<typeof useFormatCurrency>["formatCurrency"];
}) {
  return (
    <SubCard
      header={
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            {getSubscriptionStatusIcon(subscription.status)}
            <div>
              <h3 className="text-lg font-semibold text-foreground">Subscription Details</h3>
              <p className="text-sm text-muted-foreground">Service subscription information</p>
            </div>
          </div>
          <StatusPill
            label={subscription.status}
            variant={getSubscriptionStatusVariant(subscription.status)}
            size="lg"
          />
        </div>
      }
    >
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="space-y-2">
          <div className="flex items-center space-x-2">
            <CurrencyYenIcon className="h-5 w-5 text-muted-foreground" />
            <h4 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Billing Amount
            </h4>
          </div>
          <p className="text-2xl font-bold text-foreground">
            {formatCurrency(subscription.amount)}
          </p>
          <p className="text-sm text-muted-foreground">
            {getBillingCycleLabel(subscription.cycle)}
          </p>
        </div>
        <div className="space-y-2">
          <div className="flex items-center space-x-2">
            <CalendarIcon className="h-5 w-5 text-muted-foreground" />
            <h4 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Next Due Date
            </h4>
          </div>
          <p className="text-lg font-semibold text-foreground">
            {formatIsoDate(subscription.nextDue)}
          </p>
          <p className="text-sm text-muted-foreground">Due date</p>
        </div>
        <div className="space-y-2">
          <div className="flex items-center space-x-2">
            <TagIcon className="h-5 w-5 text-muted-foreground" />
            <h4 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
              Registration Date
            </h4>
          </div>
          <p className="text-lg font-semibold text-foreground">
            {formatIsoDate(subscription.registrationDate)}
          </p>
          <p className="text-sm text-muted-foreground">Service created</p>
        </div>
      </div>

      <div className="mt-6 pt-6 border-t border-border">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <div className="flex items-center space-x-2">
              <IdentificationIcon className="h-5 w-5 text-muted-foreground" />
              <h4 className="text-sm font-medium text-muted-foreground">Service ID</h4>
            </div>
            <p className="text-base font-medium text-foreground">{subscription.serviceId}</p>
          </div>
          {subscription.orderNumber && (
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <TagIcon className="h-5 w-5 text-muted-foreground" />
                <h4 className="text-sm font-medium text-muted-foreground">Order Number</h4>
              </div>
              <p className="text-base font-medium text-foreground">{subscription.orderNumber}</p>
            </div>
          )}
          {subscription.groupName && (
            <div className="space-y-2">
              <h4 className="text-sm font-medium text-muted-foreground">Product Group</h4>
              <p className="text-base font-medium text-foreground">{subscription.groupName}</p>
            </div>
          )}
          {subscription.paymentMethod && (
            <div className="space-y-2">
              <h4 className="text-sm font-medium text-muted-foreground">Payment Method</h4>
              <p className="text-base font-medium text-foreground">{subscription.paymentMethod}</p>
            </div>
          )}
        </div>
      </div>

      {subscription.customFields && Object.keys(subscription.customFields).length > 0 && (
        <div className="mt-6 pt-6 border-t border-border">
          <h4 className="text-sm font-medium text-muted-foreground mb-3">Additional Information</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {Object.entries(subscription.customFields).map(([key, value]) => (
              <div key={key} className="space-y-1">
                <p className="text-sm text-muted-foreground capitalize">
                  {key.replace(/([A-Z])/g, " $1").trim()}
                </p>
                <p className="text-sm font-medium text-foreground">{value}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {subscription.notes && (
        <div className="mt-6 pt-6 border-t border-border">
          <h4 className="text-sm font-medium text-muted-foreground mb-2">Notes</h4>
          <p className="text-sm text-foreground bg-muted rounded-md p-3">{subscription.notes}</p>
        </div>
      )}
    </SubCard>
  );
}

export const SubscriptionDetails = forwardRef<HTMLDivElement, SubscriptionDetailsProps>(
  ({ subscription, showServiceSpecificSections = true, className }, ref) => {
    const { formatCurrency } = useFormatCurrency();

    return (
      <div ref={ref} className={cn("space-y-6", className)}>
        <MainDetailsCard subscription={subscription} formatCurrency={formatCurrency} />

        {showServiceSpecificSections && (
          <>
            {isSimService(subscription.productName) && (
              <ServiceInfoCard
                title="SIM Service Information"
                heading="SIM Management Available"
                description="This subscription includes SIM management features such as data usage monitoring, top-up options, and service configuration."
                features={[
                  "Real-time data usage tracking",
                  "Data top-up and plan changes",
                  "Service feature toggles",
                  "SIM reissue options",
                ]}
                colorScheme="info"
              />
            )}
            {isInternetService(subscription.productName) && (
              <ServiceInfoCard
                title="Internet Service Information"
                heading="Internet Service Features"
                description="Your internet service includes high-speed connectivity and support options."
                features={[
                  "High-speed internet connection",
                  "24/7 technical support",
                  "Service monitoring",
                  "Installation support",
                ]}
                colorScheme="success"
              />
            )}
            {isVpnService(subscription.productName) && (
              <ServiceInfoCard
                title="VPN Service Information"
                heading="VPN Service Features"
                description="Your VPN service provides secure and private internet access."
                features={[
                  "Encrypted internet connection",
                  "Multiple server locations",
                  "No-logs policy",
                  "Multi-device support",
                ]}
                colorScheme="info"
              />
            )}
          </>
        )}
      </div>
    );
  }
);

SubscriptionDetails.displayName = "SubscriptionDetails";
