
import React, { useState, useEffect, useMemo } from 'react';
import { 
  Scale, 
  FileSignature, 
  Gavel, 
  FileText, 
  ShieldAlert, 
  Plus, 
  Printer,
  HandCoins
} from 'lucide-react';

// Modular Imports
import { LegalSummary } from './legal/LegalSummary';
import { ContractsRegistry } from './legal/ContractsRegistry';
import { CourtCases } from './legal/CourtCases';
import { PreTrialWork } from './legal/PreTrialWork';
import { ComplianceCheck } from './legal/ComplianceCheck';
import { DebtRecoveryPipeline } from './legal/DebtRecoveryPipeline';
import { allowedSubsForSection } from '../constants/permissions';

type Tab = 'summary' | 'debt' | 'contracts' | 'courts' | 'preTrial' | 'compliance';

const LEGAL_TABS: Tab[] = ['summary', 'debt', 'contracts', 'courts', 'preTrial', 'compliance'];
const SUBTAB_KEY = 'mkd_subTab_legal';

interface LegalModuleProps {
  allowedPermissions?: string[] | null;
}

export const LegalModule: React.FC<LegalModuleProps> = ({ allowedPermissions }) => {
  const visibleTabs = useMemo(() => {
    const allowed = allowedSubsForSection(allowedPermissions ?? [], 'legal');
    if (allowed === 'all') return LEGAL_TABS;
    return LEGAL_TABS.filter((t) => allowed.includes(t));
  }, [allowedPermissions]);

  const [activeTab, setActiveTab] = useState<Tab>(() => {
    const s = localStorage.getItem(SUBTAB_KEY);
    return (s && LEGAL_TABS.includes(s as Tab)) ? s as Tab : 'summary';
  });

  useEffect(() => {
    if (visibleTabs.length > 0 && !visibleTabs.includes(activeTab)) {
      setActiveTab(visibleTabs[0]);
    }
  }, [visibleTabs, activeTab]);

  useEffect(() => {
    if (visibleTabs.includes(activeTab)) localStorage.setItem(SUBTAB_KEY, activeTab);
  }, [activeTab, visibleTabs]);

  return (
    <div className="animate-fade-in pb-20">
      <div className="flex justify-between items-center mb-6 px-1">
         <div>
            <h2 className="text-xl font-bold text-slate-800 leading-none">Юридический отдел</h2>
            <p className="text-[10px] text-slate-400 font-black uppercase tracking-widest mt-1">Правовое сопровождение и взыскание</p>
         </div>
         <div className="flex gap-2">
            <button 
                className="p-2.5 bg-white border border-slate-200 text-slate-400 rounded-xl hover:text-primary-600 transition-all shadow-sm" 
                title="Печать реестров"
            >
                <Printer className="w-5 h-5"/>
            </button>
         </div>
      </div>

      {/* Sheet Selector */}
      <div className="flex p-1 bg-slate-200/50 rounded-2xl mb-6 overflow-x-auto no-scrollbar gap-1">
        {[
            { id: 'summary', label: 'Сводка', icon: Scale },
            { id: 'debt', label: 'Взыскание', icon: HandCoins },
            { id: 'contracts', label: 'Договоры', icon: FileSignature },
            { id: 'courts', label: 'Суды', icon: Gavel },
            { id: 'preTrial', label: 'Досудебная работа', icon: FileText },
            { id: 'compliance', label: 'Проверка', icon: ShieldAlert },
        ].filter((tab) => visibleTabs.includes(tab.id as Tab)).map((tab) => (
            <button 
              key={tab.id}
              onClick={() => setActiveTab(tab.id as Tab)}
              className={`flex-shrink-0 min-w-[7rem] flex items-center justify-center gap-2 py-2.5 px-4 text-[10px] font-black uppercase tracking-wider whitespace-nowrap rounded-xl transition-all ${activeTab === tab.id ? 'bg-white text-primary-600 shadow-sm border border-white' : 'text-slate-500 hover:text-slate-700'}`}
            >
              <tab.icon className="w-3.5 h-3.5"/> {tab.label}
            </button>
        ))}
      </div>

      {/* Dynamic Sheet Content */}
      <div className="min-h-[280px] sm:min-h-[360px] md:min-h-[500px]">
        {activeTab === 'summary' && <LegalSummary onNavigate={setActiveTab} />}
        {activeTab === 'debt' && <DebtRecoveryPipeline onNavigateToPreTrial={() => setActiveTab('preTrial')} />}
        {activeTab === 'contracts' && <ContractsRegistry />}
        {activeTab === 'courts' && <CourtCases />}
        {activeTab === 'preTrial' && <PreTrialWork />}
        {activeTab === 'compliance' && <ComplianceCheck />}
      </div>
    </div>
  );
};
