'use client';

import React, { useState, useEffect } from 'react';
import PageLayout from '../../components/PageLayout';
import ContractEditor from './components/contractEditor';
import ContractUploadCompanyStamp from './components/contractUploadCompanyStamp';
import ContractTemplateList from './components/contractTemplateList';
import useAuthStore from '../../store/authStore';
import { useRouter } from 'next/navigation';

const NAV = [
  { key: 'stamp', label: 'Company Stamp', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg> },
  { key: 'templates', label: 'Templates', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor"><path d="M4 6h16M4 12h16M4 18h16"/></svg> },
  { key: 'editor', label: 'Create Template', icon: <svg className="w-5 h-5" fill="none" stroke="currentColor"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/></svg> },
];

export default function ContractManagementPage() {
  const [refreshKey, setRefreshKey] = useState(0);
  const user = useAuthStore((s) => s.user);
  const [mounted, setMounted] = useState(false);
  const router = useRouter();
  const [section, setSection] = useState('templates');
  const [editingTemplateId, setEditingTemplateId] = useState<string | null>(null);

  useEffect(() => { setMounted(true); }, []);

  // Only allow admin
  const isAdmin =
    !!user &&
    (
      (user as any)?.role === 'admin' ||
      (user as any)?.userType === 'admin' ||
      (user as any)?.isAdmin === true ||
      ((user as any)?.roles?.includes?.('admin'))
    );

  useEffect(() => {
    if (mounted && !isAdmin) {
      router.replace('/');
    }
  }, [mounted, isAdmin, router]);

  if (!mounted) return null;
  if (!isAdmin) return null;

  const bumpRefresh = () => setRefreshKey((k) => k + 1);

  return (
    <PageLayout>
      <div className="bg-gradient-to-tr from-blue-50 via-white to-blue-100 min-h-screen">
        <div className="flex flex-col md:flex-row max-w-7xl mx-auto px-2 sm:px-6 lg:px-8 py-8 gap-8">
          {/* Sidebar Navigation */}
          <nav className="md:w-56 w-full flex md:flex-col flex-row gap-2 md:gap-4">
            {NAV.map((item) => (
              <button
                key={item.key}
                onClick={() => setSection(item.key)}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition
                  ${section === item.key
                    ? 'bg-blue-900 text-blue-50 shadow'
                    : 'bg-white text-blue-900 hover:bg-blue-50 hover:text-blue-900 border border-blue-200'}`}
              >
                {item.icon}
                <span>{item.label}</span>
              </button>
            ))}
          </nav>

          {/* Main Content */}
          <main className="flex-1 space-y-8">
            <header className="sticky top-0 z-10 bg-white/90 backdrop-blur border-b border-blue-100 py-10 px-8 rounded-2xl shadow-lg flex flex-col gap-4 mb-4">
              <h1 className="text-4xl font-extrabold text-blue-900 tracking-tight">Contract Management</h1>
              <p className="text-lg text-blue-700">
                Manage contract templates, company stamp, and create new templates.
              </p>
            </header>

            {/* Section Panels */}
            {section === 'stamp' && (
              <section className="rounded-2xl bg-white shadow-lg border border-gray-100 p-6">
                <h2 className="text-xl font-semibold text-blue-900 mb-4 flex items-center gap-2">
                  <svg className="w-6 h-6" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>
                  Company Stamp
                </h2>
                <ContractUploadCompanyStamp onUploaded={bumpRefresh} />
              </section>
            )}
            {section === 'templates' && (
              <section className="rounded-2xl bg-white shadow-lg border border-gray-100 p-6">
                <h2 className="text-xl font-semibold text-blue-900 mb-4 flex items-center gap-2">
                  <svg className="w-6 h-6" fill="none" stroke="currentColor"><path d="M4 6h16M4 12h16M4 18h16"/></svg>
                  Templates
                </h2>
                <ContractTemplateList
                  refreshKey={refreshKey}
                  onEdit={(id) => {
                    setEditingTemplateId(id);
                    setSection('editor');
                  }}
                />
              </section>
            )}
            {section === 'editor' && (
              <section className="rounded-2xl bg-white shadow-lg border border-gray-100 p-6">
                <h2 className="text-xl font-semibold text-blue-900 mb-4 flex items-center gap-2">
                  <svg className="w-6 h-6" fill="none" stroke="currentColor"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
                  Create Template
                </h2>
                <ContractEditor
                  editingTemplateId={editingTemplateId}
                  onCancelEdit={() => {
                    setEditingTemplateId(null);
                    setSection('templates');
                  }}
                  onSaved={(info) => {
                    bumpRefresh();
                    if (info?.action === 'revised') {
                      setEditingTemplateId(null);
                      setSection('templates');
                    }
                  }}
                />
              </section>
            )}
          </main>
        </div>
      </div>
    </PageLayout>
  );
}
