import React, { forwardRef } from "react";
import { BaseComponentProps } from "../../types";

export interface PrivacySection {
  id: string;
  title: string;
  content: string | React.ReactNode;
  subsections?: PrivacySection[];
}

export interface PrivacyPolicyProps extends BaseComponentProps {
  companyName?: string;
  contactEmail?: string;
  lastUpdated?: string;
  sections?: PrivacySection[];
  showTableOfContents?: boolean;
  enablePrint?: boolean;
}

const defaultSections: PrivacySection[] = [
  {
    id: "information-collection",
    title: "Information We Collect",
    content:
      "We collect information you provide directly to us, such as when you create an account, make a purchase, or contact us for support.",
    subsections: [
      {
        id: "personal-information",
        title: "Personal Information",
        content:
          "This may include your name, email address, postal address, phone number, and other similar contact data.",
      },
      {
        id: "usage-data",
        title: "Usage Data",
        content:
          "We automatically collect certain information about your interaction with our services, such as your IP address, browser type, and pages visited.",
      },
    ],
  },
  {
    id: "information-use",
    title: "How We Use Your Information",
    content:
      "We use the information we collect to provide, maintain, and improve our services, process transactions, and communicate with you.",
  },
  {
    id: "information-sharing",
    title: "Information Sharing and Disclosure",
    content:
      "We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy.",
  },
  {
    id: "data-security",
    title: "Data Security",
    content:
      "We implement appropriate technical and organizational measures to protect your personal information against unauthorized access, alteration, disclosure, or destruction.",
  },
  {
    id: "your-rights",
    title: "Your Rights",
    content:
      "You have the right to access, update, or delete your personal information. You may also opt-out of certain communications from us.",
  },
  {
    id: "contact-us",
    title: "Contact Us",
    content:
      "If you have any questions about this Privacy Policy, please contact us at the email address provided below.",
  },
];

export const PrivacyPolicy = forwardRef<HTMLDivElement, PrivacyPolicyProps>(
  (
    {
      className = "",
      companyName = "Your Company",
      contactEmail = "privacy@yourcompany.com",
      lastUpdated = new Date().toISOString().split("T")[0],
      sections = defaultSections,
      showTableOfContents = true,
      enablePrint = true,
      ...props
    },
    ref
  ) => {
    const handlePrint = () => {
      window.print();
    };

    const renderSection = (section: PrivacySection, level = 1) => {
      const headingLevel = Math.min(level + 1, 6);

      return (
        <section key={section.id} id={section.id} className="mb-8">
          {headingLevel === 2 && (
            <h2 className="mb-4 font-semibold text-gray-900 dark:text-white text-2xl">
              {section.title}
            </h2>
          )}
          {headingLevel === 3 && (
            <h3 className="mb-4 font-semibold text-gray-900 dark:text-white text-xl">
              {section.title}
            </h3>
          )}
          {headingLevel === 4 && (
            <h4 className="mb-4 font-semibold text-gray-900 dark:text-white text-lg">
              {section.title}
            </h4>
          )}
          {headingLevel === 5 && (
            <h5 className="mb-4 font-semibold text-gray-900 dark:text-white text-base">
              {section.title}
            </h5>
          )}
          {headingLevel === 6 && (
            <h6 className="mb-4 font-semibold text-gray-900 dark:text-white text-sm">
              {section.title}
            </h6>
          )}

          <div className="mb-4 text-gray-700 dark:text-gray-300 leading-relaxed">
            {typeof section.content === "string" ? (
              <p>{section.content}</p>
            ) : (
              section.content
            )}
          </div>

          {section.subsections && section.subsections.length > 0 && (
            <div className="ml-4 border-l-2 border-gray-200 dark:border-gray-700 pl-6">
              {section.subsections.map((subsection) =>
                renderSection(subsection, level + 1)
              )}
            </div>
          )}
        </section>
      );
    };

    const renderTableOfContents = () => {
      if (!showTableOfContents) return null;

      const renderTocItem = (section: PrivacySection, level = 0) => (
        <li key={section.id} className={level > 0 ? "ml-4" : ""}>
          <a
            href={`#${section.id}`}
            className="text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300 transition-colors"
          >
            {section.title}
          </a>
          {section.subsections && section.subsections.length > 0 && (
            <ul className="mt-1 space-y-1">
              {section.subsections.map((subsection) =>
                renderTocItem(subsection, level + 1)
              )}
            </ul>
          )}
        </li>
      );

      return (
        <div className="mb-8 p-6 bg-gray-50 dark:bg-gray-800 rounded-lg">
          <h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">
            Table of Contents
          </h2>
          <ul className="space-y-2">
            {sections.map((section) => renderTocItem(section))}
          </ul>
        </div>
      );
    };

    return (
      <div
        ref={ref}
        className={`max-w-4xl mx-auto p-6 ${className}`}
        {...props}
      >
        {/* Header */}
        <div className="mb-8 text-center border-b border-gray-200 dark:border-gray-700 pb-8">
          <h1 className="text-3xl font-bold mb-2 text-gray-900 dark:text-white">
            Privacy Policy
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mb-4">{companyName}</p>
          <p className="text-sm text-gray-500 dark:text-gray-500">
            Last updated: {lastUpdated}
          </p>

          {enablePrint && (
            <div className="mt-4">
              <button
                onClick={handlePrint}
                className="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 transition-colors print:hidden"
              >
                <svg
                  className="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"
                  />
                </svg>
                Print Policy
              </button>
            </div>
          )}
        </div>

        {/* Table of Contents */}
        {renderTableOfContents()}

        {/* Content */}
        <div className="prose dark:prose-invert max-w-none">
          {sections.map((section) => renderSection(section))}
        </div>

        {/* Footer */}
        <div className="mt-12 pt-8 border-t border-gray-200 dark:border-gray-700">
          <div className="text-center">
            <h3 className="text-lg font-semibold mb-2 text-gray-900 dark:text-white">
              Questions or Concerns?
            </h3>
            <p className="text-gray-600 dark:text-gray-400">
              If you have any questions about this Privacy Policy, please
              contact us at{" "}
              <a
                href={`mailto:${contactEmail}`}
                className="text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300"
              >
                {contactEmail}
              </a>
            </p>
          </div>
        </div>
      </div>
    );
  }
);

PrivacyPolicy.displayName = "PrivacyPolicy";
