'use client';

import { TemplateEditor } from '@/components/numbering/template-editor';
import { numberingApi, NumberingTemplate } from '@/lib/api/numbering';
import { useRouter } from 'next/navigation';
import { useCorrespondenceTypes, useContracts, useDisciplines } from '@/hooks/use-master-data';
import { useProjects } from '@/hooks/use-projects';
import { toast } from 'sonner';
import { Contract, getContractPublicId } from '@/types/contract';

export default function NewTemplatePage() {
  const router = useRouter();

  // Master Data
  const { data: correspondenceTypes = [] } = useCorrespondenceTypes();
  const { data: projects = [] } = useProjects();
  const projectId = 1; // Default or sync with selection
  const { data: contractsData } = useContracts(projectId);
  const contracts = (Array.isArray(contractsData) ? contractsData : []) as Contract[];
  const firstContract = contracts[0];
  const contractId = getContractPublicId(firstContract);
  const { data: disciplines = [] } = useDisciplines(contractId);

  const selectedProjectName =
    projects.find((p: { id?: number; publicId?: string; projectName: string }) =>
      String(p.publicId ?? p.id) === String(projectId))?.projectName || 'LCBP3';

  const handleSave = async (data: Partial<NumberingTemplate>) => {
    try {
      // Correcting type mismatch by ensuring all required fields for SaveTemplateDto are present
      await numberingApi.saveTemplate({
        projectId: data.projectId!,
        correspondenceTypeId: data.correspondenceTypeId ?? null,
        formatTemplate: data.formatTemplate!,
        disciplineId: data.disciplineId,
        description: data.description,
        resetSequenceYearly: data.resetSequenceYearly,
        isActive: data.isActive,
      });
      router.push('/admin/doc-control/numbering');
    } catch (_error) {
      toast.error('Failed to create template');
    }
  };

  const handleCancel = () => {
    router.push('/admin/doc-control/numbering');
  };

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-3xl font-bold">New Numbering Template</h1>
      <TemplateEditor
        projectId={projectId}
        projectName={selectedProjectName}
        correspondenceTypes={correspondenceTypes}
        disciplines={disciplines}
        onSave={handleSave}
        onCancel={handleCancel}
      />
    </div>
  );
}
