import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { MainLayout } from '@/components/layout/MainLayout.tsx';
import PageHeader from '@/components/layout/PageHeader.tsx';
import CreateProposalModal from '@/components/organization/CreateProposalModal.tsx';
import OrganizationContent from '@/components/organization/OrganizationContent.tsx';
import OrganizationSidebar from '@/components/organization/OrganizationSidebar.tsx';
import OrganizationPageSkeleton from '@/components/organization/skeletons/OrganizationPageSkeleton.tsx';
import { Container, Grid, Stack } from '@/components/ui/layout';
import { useOrganizationData } from '@/hooks/pages/useOrganizationData.ts';
import { useOrganizationPage } from '@/hooks/pages/useOrganizationPage.ts';

const OrganizationPage = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { organization, relatedLandmark, similarOrgs, isLoading } = useOrganizationData(id);

  const {
    symbiosisState,
    proposalState,
    handleAnalyzeSymbiosis,
    handleFetchWebIntelligence,
    handleSelectOrg,
    handleUpdateOrganization,
    handleMapNavigation,
  } = useOrganizationPage(organization);

  useEffect(() => {
    if (!isLoading && !organization) {
      navigate('/map');
    }
  }, [organization, isLoading, navigate]);

  if (isLoading) {
    return <OrganizationPageSkeleton />;
  }

  if (!organization) {
    return null;
  }

  const handleFooterNavigate = (page: 'about' | 'contact' | 'privacy') => {
    navigate(`/${page}`);
  };

  return (
    <MainLayout className="bg-muted/30" onNavigate={handleFooterNavigate}>
      <Container size="xl" className="py-12">
        <PageHeader title={organization.Name} onBack={() => navigate(-1)} />
        <Grid cols={{ lg: 3 }} gap="2xl" align="start">
          <OrganizationContent
            organization={organization}
            relatedLandmark={relatedLandmark}
            symbiosisState={symbiosisState}
            handleUpdateOrganization={handleUpdateOrganization}
            handleMapNavigation={handleMapNavigation}
            handleSelectOrg={handleSelectOrg}
            handleAnalyzeSymbiosis={handleAnalyzeSymbiosis}
            handleFetchWebIntelligence={handleFetchWebIntelligence}
          />

          {/* Sidebar */}
          <Stack spacing="2xl" className="lg:sticky lg:top-24">
            <OrganizationSidebar
              organization={organization}
              similarOrgs={Array.isArray(similarOrgs) ? similarOrgs : []}
              onSelectOrg={handleSelectOrg}
            />
          </Stack>
        </Grid>
      </Container>

      <CreateProposalModal
        isOpen={proposalState.isModalOpen}
        onClose={proposalState.closeModal}
        context={proposalState.modalContext}
        onSubmit={proposalState.submitProposal}
      />
    </MainLayout>
  );
};

export default OrganizationPage;
