'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import IssueManagementListClient from '@/components/business/construction/issue-management/IssueManagementListClient';
import IssueDetailForm from '@/components/business/construction/issue-management/IssueDetailForm';
import {
  getIssueList,
  getIssueStats,
} from '@/components/business/construction/issue-management/actions';
import type {
  Issue,
  IssueStats,
} from '@/components/business/construction/issue-management/types';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

export default function IssueManagementPage() {
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode');

  const [data, setData] = useState<Issue[]>([]);
  const [stats, setStats] = useState<IssueStats | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (mode !== 'new') {
      const loadData = async () => {
        try {
          const [listResult, statsResult] = await Promise.all([
            getIssueList({ size: 1000 }),
            getIssueStats(),
          ]);

          if (listResult.success && listResult.data) {
            setData(listResult.data.items);
          }
          if (statsResult.success && statsResult.data) {
            setStats(statsResult.data);
          }
        } catch (error) {
          console.error('Failed to load issue management data:', error);
        } finally {
          setIsLoading(false);
        }
      };

      loadData();
    } else {
      setIsLoading(false);
    }
  }, [mode]);

  if (mode === 'new') {
    return <IssueDetailForm mode="create" />;
  }

  if (isLoading) return <GenericPageSkeleton />;

  return <IssueManagementListClient initialData={data} initialStats={stats} />;
}
