"use client";

import React from "react";
import {
  DevicePhoneMobileIcon,
  WifiIcon,
  SignalIcon,
  ClockIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  XCircleIcon,
} from "@heroicons/react/24/outline";
import type { SimDetails } from "@customer-portal/domain/sim";
import { formatIsoDate } from "@/shared/utils";

// Re-export for backwards compatibility
export type { SimDetails };

// Inline formatPlanShort function
function formatPlanShort(planCode?: string): string {
  if (!planCode) return "—";
  const m = planCode.match(/(?:^|[_-])(\d+(?:\.\d+)?)\s*G(?:B)?\b/i);
  if (m && m[1]) {
    return `${m[1]}G`;
  }
  // Try extracting trailing number+G anywhere in the string
  const m2 = planCode.match(/(\d+(?:\.\d+)?)\s*G(?:B)?\b/i);
  if (m2 && m2[1]) {
    return `${m2[1]}G`;
  }
  return planCode;
}

interface SimDetailsCardProps {
  simDetails: SimDetails;
  isLoading?: boolean;
  error?: string | null;
  embedded?: boolean; // when true, render content without card container
  showFeaturesSummary?: boolean; // show the right-side Service Features summary
}

export function SimDetailsCard({
  simDetails,
  isLoading,
  error,
  embedded = false,
  showFeaturesSummary = true,
}: SimDetailsCardProps) {
  const formatPlan = (code?: string) => {
    const formatted = formatPlanShort(code);
    // Remove "PASI" prefix if present
    return formatted?.replace(/^PASI\s*/, "") || formatted;
  };
  const getStatusIcon = (status: string) => {
    switch (status) {
      case "active":
        return <CheckCircleIcon className="h-6 w-6 text-success" />;
      case "suspended":
        return <ExclamationTriangleIcon className="h-6 w-6 text-warning" />;
      case "cancelled":
        return <XCircleIcon className="h-6 w-6 text-danger" />;
      case "pending":
        return <ClockIcon className="h-6 w-6 text-info" />;
      default:
        return <DevicePhoneMobileIcon className="h-6 w-6 text-muted-foreground" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "active":
        return "bg-success-soft text-success";
      case "suspended":
        return "bg-warning-soft text-warning";
      case "cancelled":
        return "bg-danger-soft text-danger";
      case "pending":
        return "bg-info-soft text-info";
      default:
        return "bg-muted text-muted-foreground";
    }
  };

  const formatDate = (dateString: string) => {
    const formatted = formatIsoDate(dateString, { fallback: dateString, dateStyle: "medium" });
    return formatted === "Invalid date" ? dateString : formatted;
  };

  const formatQuota = (quotaMb: number) => {
    if (quotaMb >= 1000) {
      return `${(quotaMb / 1000).toFixed(1)} GB`;
    }
    return `${quotaMb.toFixed(0)} MB`;
  };

  if (isLoading) {
    const Skeleton = (
      <div
        className={`${embedded ? "" : "bg-card shadow-sm rounded-[var(--cp-card-radius)] border border-border hover:shadow-md transition-shadow duration-[var(--cp-transition-normal)] "}p-[var(--cp-card-padding)] lg:p-[var(--cp-card-padding-lg)]`}
      >
        <div className="animate-pulse">
          <div className="flex items-center space-x-4">
            <div className="rounded-full bg-gradient-to-br from-primary-soft to-accent-soft h-14 w-14"></div>
            <div className="flex-1 space-y-3">
              <div className="h-5 bg-gradient-to-r from-muted to-muted-hover rounded-[var(--cp-radius-md)] w-3/4"></div>
              <div className="h-4 bg-gradient-to-r from-muted to-muted-hover rounded-[var(--cp-radius-md)] w-1/2"></div>
            </div>
          </div>
          <div className="mt-8 space-y-4">
            <div className="h-4 bg-gradient-to-r from-muted to-muted-hover rounded-[var(--cp-radius-md)]"></div>
            <div className="h-4 bg-gradient-to-r from-muted to-muted-hover rounded-[var(--cp-radius-md)] w-5/6"></div>
            <div className="h-4 bg-gradient-to-r from-muted to-muted-hover rounded-[var(--cp-radius-md)] w-4/6"></div>
          </div>
        </div>
      </div>
    );
    return Skeleton;
  }

  if (error) {
    return (
      <div
        className={`${embedded ? "" : "bg-card shadow-sm rounded-[var(--cp-card-radius)] border border-danger-soft "}p-[var(--cp-card-padding)] lg:p-[var(--cp-card-padding-lg)]`}
      >
        <div className="text-center">
          <div className="bg-danger-soft rounded-full p-3 w-16 h-16 mx-auto mb-4">
            <ExclamationTriangleIcon className="h-10 w-10 text-danger mx-auto" />
          </div>
          <h3 className="text-lg font-semibold text-foreground mb-2">Error Loading SIM Details</h3>
          <p className="text-danger text-sm">{error}</p>
        </div>
      </div>
    );
  }

  // Modern eSIM details view with usage visualization
  if (simDetails.simType === "esim") {
    const remainingGB = simDetails.remainingQuotaMb / 1000;
    const totalGB = 1048.6; // Mock total - should come from API
    const usedGB = totalGB - remainingGB;
    const usagePercentage = (usedGB / totalGB) * 100;

    // Usage Donut Component
    const UsageDonut = ({ size = 120 }: { size?: number }) => {
      const radius = (size - 16) / 2;
      const circumference = 2 * Math.PI * radius;
      const strokeDashoffset = circumference - (usagePercentage / 100) * circumference;

      return (
        <div className="relative flex items-center justify-center">
          <svg width={size} height={size} className="transform -rotate-90">
            <circle
              cx={size / 2}
              cy={size / 2}
              r={radius}
              fill="none"
              stroke="currentColor"
              strokeWidth="8"
              className="text-muted"
            />
            <circle
              cx={size / 2}
              cy={size / 2}
              r={radius}
              fill="none"
              stroke="currentColor"
              strokeWidth="8"
              strokeLinecap="round"
              strokeDasharray={circumference}
              strokeDashoffset={strokeDashoffset}
              className="text-primary transition-all duration-[var(--cp-transition-normal)]"
            />
          </svg>
          <div className="absolute text-center">
            <div className="text-3xl font-semibold text-foreground">{remainingGB.toFixed(1)}</div>
            <div className="text-sm text-muted-foreground -mt-1">GB remaining</div>
            <div className="text-xs text-muted-foreground mt-1">
              {usagePercentage.toFixed(1)}% used
            </div>
          </div>
        </div>
      );
    };

    return (
      <div
        className={`${embedded ? "" : "bg-card shadow-sm rounded-[var(--cp-card-radius)] border border-border"}`}
      >
        {/* Compact Header Bar */}
        <div
          className={`${embedded ? "" : "px-[var(--cp-space-6)] py-[var(--cp-space-4)] border-b border-border"}`}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <span
                className={`inline-flex px-3 py-1 text-xs font-medium rounded-full ${getStatusColor(simDetails.status)}`}
              >
                {simDetails.status.charAt(0).toUpperCase() + simDetails.status.slice(1)}
              </span>
              <span className="text-lg font-semibold text-foreground">
                {formatPlan(simDetails.planCode)}
              </span>
            </div>
          </div>
          <div className="text-sm text-muted-foreground mt-1">{simDetails.msisdn}</div>
        </div>

        <div className={`${embedded ? "" : "px-[var(--cp-space-6)] py-[var(--cp-space-6)]"}`}>
          {/* Usage Visualization */}
          <div className="flex justify-center mb-6">
            <UsageDonut size={160} />
          </div>

          <div className="border-t border-border pt-4">
            <h4 className="text-sm font-medium text-foreground mb-3">Recent Usage History</h4>
            <div className="space-y-2">
              {[
                { date: "Sep 29", usage: "0 MB" },
                { date: "Sep 28", usage: "0 MB" },
                { date: "Sep 27", usage: "0 MB" },
              ].map((entry, index) => (
                <div key={index} className="flex justify-between items-center text-xs">
                  <span className="text-muted-foreground">{entry.date}</span>
                  <span className="text-foreground">{entry.usage}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Default view for physical SIM cards
  return (
    <div
      className={`${embedded ? "" : "bg-card shadow-sm rounded-[var(--cp-card-radius)] border border-border"}`}
    >
      {/* Header */}
      <div
        className={`${embedded ? "" : "px-[var(--cp-space-6)] py-[var(--cp-space-4)] border-b border-border"}`}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <div className="text-2xl mr-3">
              <DevicePhoneMobileIcon className="h-8 w-8 text-primary" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-foreground">Physical SIM Details</h3>
              <p className="text-sm text-muted-foreground">
                {formatPlan(simDetails.planCode)} • {`${simDetails.simType} SIM`}
              </p>
            </div>
          </div>
          <div className="flex items-center space-x-3">
            {getStatusIcon(simDetails.status)}
            <span
              className={`inline-flex px-3 py-1 text-sm font-semibold rounded-full ${getStatusColor(simDetails.status)}`}
            >
              {simDetails.status.charAt(0).toUpperCase() + simDetails.status.slice(1)}
            </span>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className={`${embedded ? "" : "px-[var(--cp-space-6)] py-[var(--cp-space-4)]"}`}>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* SIM Information */}
          <div>
            <h4 className="text-sm font-medium text-muted-foreground uppercase tracking-wider mb-3">
              SIM Information
            </h4>
            <div className="space-y-3">
              <div>
                <label className="text-xs text-muted-foreground">Phone Number</label>
                <p className="text-sm font-medium text-foreground">{simDetails.msisdn}</p>
              </div>

              <div>
                <label className="text-xs text-muted-foreground">ICCID</label>
                <p className="text-sm font-mono text-foreground break-all">{simDetails.iccid}</p>
              </div>

              {simDetails.eid && (
                <div>
                  <label className="text-xs text-muted-foreground">EID (eSIM)</label>
                  <p className="text-sm font-mono text-foreground break-all">{simDetails.eid}</p>
                </div>
              )}

              {simDetails.imsi && (
                <div>
                  <label className="text-xs text-muted-foreground">IMSI</label>
                  <p className="text-sm font-mono text-foreground">{simDetails.imsi}</p>
                </div>
              )}

              {simDetails.activatedAt && (
                <div>
                  <label className="text-xs text-muted-foreground">Service Start Date</label>
                  <p className="text-sm text-foreground">{formatDate(simDetails.activatedAt)}</p>
                </div>
              )}
            </div>
          </div>

          {/* Service Features */}
          {showFeaturesSummary && (
            <div>
              <h4 className="text-sm font-medium text-muted-foreground uppercase tracking-wider mb-3">
                Service Features
              </h4>
              <div className="space-y-3">
                <div>
                  <label className="text-xs text-muted-foreground">Data Remaining</label>
                  <p className="text-lg font-semibold text-success">
                    {formatQuota(simDetails.remainingQuotaMb)}
                  </p>
                </div>

                {simDetails.hasVoice === false ? (
                  <p className="text-sm text-muted-foreground">
                    Data-only plan (no voice features)
                  </p>
                ) : (
                  <>
                    <div className="flex items-center space-x-4">
                      <div className="flex items-center">
                        <SignalIcon
                          className={`h-4 w-4 mr-1 ${simDetails.voiceMailEnabled ? "text-success" : "text-muted-foreground"}`}
                        />
                        <span
                          className={`text-sm ${simDetails.voiceMailEnabled ? "text-success" : "text-muted-foreground"}`}
                        >
                          Voicemail {simDetails.voiceMailEnabled ? "Enabled" : "Disabled"}
                        </span>
                      </div>
                      <div className="flex items-center">
                        <DevicePhoneMobileIcon
                          className={`h-4 w-4 mr-1 ${simDetails.callWaitingEnabled ? "text-success" : "text-muted-foreground"}`}
                        />
                        <span
                          className={`text-sm ${simDetails.callWaitingEnabled ? "text-success" : "text-muted-foreground"}`}
                        >
                          Call Waiting {simDetails.callWaitingEnabled ? "Enabled" : "Disabled"}
                        </span>
                      </div>
                    </div>

                    <div className="flex items-center">
                      <WifiIcon
                        className={`h-4 w-4 mr-1 ${simDetails.internationalRoamingEnabled ? "text-success" : "text-muted-foreground"}`}
                      />
                      <span
                        className={`text-sm ${simDetails.internationalRoamingEnabled ? "text-success" : "text-muted-foreground"}`}
                      >
                        Int&apos;l Roaming{" "}
                        {simDetails.internationalRoamingEnabled ? "Enabled" : "Disabled"}
                      </span>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Expiry Date */}
        {simDetails.expiresAt && (
          <div className="mt-6 pt-6 border-t border-border">
            <div className="flex items-center text-sm">
              <ClockIcon className="h-4 w-4 text-warning mr-2" />
              <span className="text-warning-foreground">
                Expires on {formatDate(simDetails.expiresAt)}
              </span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
