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

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

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

const defaultSections: TermsSection[] = [
  {
    id: "acceptance",
    title: "Acceptance of Terms",
    content:
      "By accessing and using our service, you accept and agree to be bound by the terms and provision of this agreement.",
  },
  {
    id: "use-license",
    title: "Use License",
    content:
      "Permission is granted to temporarily use our service for personal, non-commercial transitory viewing only.",
    subsections: [
      {
        id: "license-restrictions",
        title:
          "This license shall automatically terminate if you violate any of these restrictions",
        content:
          "You may not: modify or copy the materials; use the materials for any commercial purpose; attempt to reverse engineer any software; remove any copyright or proprietary notations.",
      },
    ],
  },
  {
    id: "disclaimer",
    title: "Disclaimer",
    content:
      "The materials on our service are provided on an 'as is' basis. We make no warranties, expressed or implied, and hereby disclaim all other warranties including, without limitation, implied warranties or conditions of merchantability, fitness for a particular purpose, or non-infringement of intellectual property or other violation of rights.",
  },
  {
    id: "limitations",
    title: "Limitations",
    content:
      "In no event shall our company or its suppliers be liable for any damages (including, without limitation, damages for loss of data or profit, or due to business interruption) arising out of the use or inability to use our service.",
  },
  {
    id: "accuracy",
    title: "Accuracy of Materials",
    content:
      "The materials appearing on our service could include technical, typographical, or photographic errors. We do not warrant that any of the materials are accurate, complete, or current.",
  },
  {
    id: "links",
    title: "Links",
    content:
      "We have not reviewed all of the sites linked to our service and are not responsible for the contents of any such linked site. The inclusion of any link does not imply endorsement by us of the site.",
  },
  {
    id: "modifications",
    title: "Modifications",
    content:
      "We may revise these terms of service at any time without notice. By using this service, you are agreeing to be bound by the then current version of these terms of service.",
  },
  {
    id: "governing-law",
    title: "Governing Law",
    content:
      "These terms and conditions are governed by and construed in accordance with the laws and you irrevocably submit to the exclusive jurisdiction of the courts in that state or location.",
  },
];

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

    const renderSection = (section: TermsSection, 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: TermsSection, 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">
            Terms of Service
          </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 Terms
              </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 About These Terms?
            </h3>
            <p className="text-gray-600 dark:text-gray-400">
              If you have any questions about these Terms of Service, 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>
    );
  }
);

TermsOfService.displayName = "TermsOfService";
