'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { DomainSettingsContent } from '@/components/settings/DomainSettingsContent';
import { hasCustomDomainAccess } from '@/lib/cms/types';
import styles from '../dashboard.module.css';

interface DealerInfo {
  subscriptionTier: string;
  hasGrandfatheredCustomDomain: boolean;
}

export default function SettingsPage() {
  const { status } = useSession();
  const router = useRouter();
  const [dealer, setDealer] = useState<DealerInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [expandedSection, setExpandedSection] = useState<string | null>(null);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/api/auth/signin');
    }
  }, [status, router]);

  useEffect(() => {
    if (status === 'authenticated') {
      fetchDealer();
    }
  }, [status]);

  async function fetchDealer() {
    try {
      const response = await fetch('/api/dealer');
      if (response.ok) {
        const data = await response.json();
        setDealer(data);
      }
    } catch (error) {
      console.error('Failed to fetch dealer:', error);
    } finally {
      setLoading(false);
    }
  }

  function toggleSection(section: string) {
    setExpandedSection(expandedSection === section ? null : section);
  }

  if (status === 'loading' || loading) {
    return (
      <section className={styles.section}>
        <div className={styles.content}>
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-500"></div>
          </div>
        </div>
      </section>
    );
  }

  const hasDomainAccess =
    dealer && hasCustomDomainAccess(dealer.subscriptionTier, dealer.hasGrandfatheredCustomDomain);

  const isDomainExpanded = expandedSection === 'domains';

  return (
    <section className={styles.section}>
      <div className={styles.content}>
        <Link href="/dashboard" className={styles.backLink}>
          <svg className={styles.backIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 19l-7-7 7-7"
            />
          </svg>
          Back to Dashboard
        </Link>
        <h1 className="text-2xl font-bold mb-6">Settings</h1>

        <div className="grid gap-4">
          {/* Domain Settings Accordion */}
          <div className="bg-slate-800 rounded-lg overflow-hidden">
            <button
              onClick={() => toggleSection('domains')}
              className="w-full p-6 text-left hover:bg-slate-700/50 transition-colors"
              aria-expanded={isDomainExpanded}
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-lg bg-cyan-900/50 flex items-center justify-center">
                    <svg
                      className="w-6 h-6 text-cyan-400"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <circle cx="12" cy="12" r="10" />
                      <line x1="2" y1="12" x2="22" y2="12" />
                      <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
                    </svg>
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-white">Domain Settings</h2>
                    <p className="text-sm text-gray-400">
                      {hasDomainAccess
                        ? 'Manage your subdomain and custom domain'
                        : 'View your subdomain (upgrade to Growth for custom domains)'}
                    </p>
                  </div>
                </div>
                <svg
                  className={`w-5 h-5 text-gray-400 transition-transform duration-200 ${
                    isDomainExpanded ? 'rotate-180' : ''
                  }`}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polyline points="6 9 12 15 18 9" />
                </svg>
              </div>
            </button>

            {/* Accordion Content */}
            <div
              className={`overflow-hidden transition-all duration-300 ease-in-out ${
                isDomainExpanded ? 'max-h-[2000px] opacity-100' : 'max-h-0 opacity-0'
              }`}
            >
              <div className="px-6 pb-6 border-t border-slate-700">
                <div className="pt-6">
                  <DomainSettingsContent isAuthenticated={status === 'authenticated'} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
