import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Plus, Trash2, Save, FileText, Pencil, Check, X, CalendarIcon } from 'lucide-react';
import { format } from 'date-fns';
import { toast } from 'sonner';
import {
  Button,
  Input,
  Textarea,
  Card,
  CardContent,
  CardTitle,
  Checkbox,
  Label,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableFooter,
  Popover,
  PopoverContent,
  PopoverTrigger,
  Calendar,
  cn,
  collectContributionDigitalSignaturePrerequisiteGaps,
  formatApplicantPrerequisiteToastDescription,
  type ApplicantPrefill,
  useOptionalDraft,
  canonicalMainAuthorFromDraft,
  pushMainAuthorToDraft,
  reconcileRepresentativeAuthorSlices,
  type Author,
  authorToContributionRow,
  contributionColumnToAuthorField,
  createEmptyAuthorRow,
  normalizeContributionPercent,
} from '@ump/shared';
import { exportDraftPdf } from '@/components/applicant/initiative-draft/pdfExport';

interface Participant {
  id: number;
  fullName: string;
  workUnit: string;
  contributionPercent: number;
  isEditing: boolean;
}

interface ContributionFormState {
  initiativeName: string;
  mainAuthor: string;
  position: string;
  representativePercent: number;
  submissionDate: Date;
  participants: Participant[];
  digitalSignatureConfirmed: boolean;
}

interface ContributionConfirmationFormProps {
  onVerify?: (fieldName: string, content: string) => void;
  /** When true, all fields are non-interactive (e.g. staff review). */
  readOnly?: boolean;
  showVerifyButton?: boolean; // Only Admin can see verify button
  applicantPrefill?: ApplicantPrefill;
  initialDraft?: Partial<ContributionFormState>;
  onSaveDraft?: (data: ContributionFormState) => Promise<void>;
  autoSaveDebounceMs?: number;
  /** After a successful save (e.g. Dashboard switches to « Xem lại & tải PDF »). */
  onNext?: () => void;
  /**
   * When there is no DraftProvider (e.g. admin case review), pass the Đơn tab `authors` array
   * so this table matches « Đơn Đề nghị Công nhận ». Ignored whenever a draft context exists.
   */
  mirrorApplicationAuthors?: Author[];
  /**
   * When there is no DraftProvider, pass `application.initiativeName` from the Đơn tab JSON
   * so this field matches tab « Đơn Đề nghị ». Omit in applicant flow. Ignored when a draft context exists.
   */
  mirrorInitiativeNameFromApplication?: string;
}

const initialFormState: ContributionFormState = {
  initiativeName: '',
  mainAuthor: '',
  position: '',
  representativePercent: 0,
  submissionDate: new Date(),
  participants: [],
  digitalSignatureConfirmed: false,
};

export default function ContributionConfirmationForm({
  onVerify,
  readOnly = false,
  showVerifyButton = false,
  applicantPrefill,
  initialDraft,
  onSaveDraft,
  autoSaveDebounceMs,
  onNext,
  mirrorApplicationAuthors: mirrorApplicationAuthorsProp,
  mirrorInitiativeNameFromApplication: mirrorInitiativeNameFromApplicationProp,
}: ContributionConfirmationFormProps) {
  const draftCtx = useOptionalDraft();
  const draftCtxRef = useRef(draftCtx);
  draftCtxRef.current = draftCtx;

  const draft = draftCtx?.draft;
  const draftId = draft?.draftId;
  const updateReport = draftCtx?.updateReport;
  const hasDraftContext = draftCtx != null;

  const [formData, setFormData] = useState<ContributionFormState>(initialFormState);
  const autoSaveSkipRef = useRef(true);
  const [editingRow, setEditingRow] = useState<Participant | null>(null);
  /** Đơn §1 authors — edit row / cancel backup when table is driven by draft */
  const [editingAuthorId, setEditingAuthorId] = useState<number | null>(null);
  const [authorEditBackup, setAuthorEditBackup] = useState<Author | null>(null);
  const [isSavingDraft, setIsSavingDraft] = useState(false);

  useEffect(() => {
    if (hasDraftContext) return;
    if (!applicantPrefill) return;
    setFormData((prev) => ({
      ...prev,
      ...(applicantPrefill.initiativeName ? { initiativeName: applicantPrefill.initiativeName } : {}),
      ...(applicantPrefill.authorName ? { mainAuthor: applicantPrefill.authorName } : {}),
    }));
  }, [hasDraftContext, applicantPrefill?.initiativeName, applicantPrefill?.authorName]);

  useEffect(() => {
    if (hasDraftContext) return;
    if (!initialDraft) return;
    setFormData((prev) => ({ ...prev, ...initialDraft }));
  }, [hasDraftContext, initialDraft]);

  useEffect(() => {
    if (!onSaveDraft || !autoSaveDebounceMs || readOnly) return;
    if (autoSaveSkipRef.current) {
      autoSaveSkipRef.current = false;
      return;
    }
    const id = window.setTimeout(() => {
      void (async () => {
        try {
          await onSaveDraft(formData);
        } catch (e) {
          console.error("Đóng góp — tự động lưu bản nháp thất bại:", e);
        }
      })();
    }, autoSaveDebounceMs);
    return () => window.clearTimeout(id);
  }, [formData, onSaveDraft, autoSaveDebounceMs, readOnly]);

  const handleSaveDraft = async () => {
    if (isSavingDraft) return;
    setIsSavingDraft(true);
    try {
      if (onSaveDraft) {
        await onSaveDraft(formData);
      }
      toast.success('Đã lưu bản nháp xác nhận đóng góp.');
      onNext?.();
    } finally {
      setIsSavingDraft(false);
    }
  };

  const handleExportCurrentPdf = async () => {
    if (!draftCtx) {
      toast.error('Không tìm thấy dữ liệu bản nháp để xuất PDF.');
      return;
    }
    try {
      await exportDraftPdf(draftCtx.draft, draftCtx.caseId);
      toast.success('Đã xuất PDF hồ sơ hiện tại.');
    } catch {
      toast.error('Không thể xuất PDF hồ sơ hiện tại.');
    }
  };


  const applicationAuthors = draft?.application.authors;

  /** Same idea as `applicationAuthors` from DraftProvider: admin review passes Đơn `authors` explicitly. */
  const mirrorsFromApplication =
    !draftCtx &&
    Array.isArray(mirrorApplicationAuthorsProp) &&
    mirrorApplicationAuthorsProp.length > 0;
  const mirrorApplicationAuthors = mirrorsFromApplication
    ? mirrorApplicationAuthorsProp
    : undefined;

  const mirrorsInitiativeNameFromApplication =
    !draftCtx && mirrorInitiativeNameFromApplicationProp !== undefined;

  /** Rows for § “Tỷ Lệ Đóng Góp”: mirror Đơn §1 `authors` when a draft exists (or when `mirrorApplicationAuthors` is set). */
  const tableParticipants = useMemo((): Participant[] => {
    if (hasDraftContext && applicationAuthors) {
      if (applicationAuthors.length === 0) return [];
      return applicationAuthors.map((a) =>
        authorToContributionRow(a, editingAuthorId === a.id),
      );
    }
    if (mirrorsFromApplication && mirrorApplicationAuthors) {
      return mirrorApplicationAuthors.map((a) => authorToContributionRow(a, false));
    }
    return formData.participants;
  }, [
    hasDraftContext,
    applicationAuthors,
    formData.participants,
    editingAuthorId,
    mirrorsFromApplication,
    mirrorApplicationAuthors,
  ]);

  const totalPercent = useMemo(() => {
    if (hasDraftContext && draft) {
      return draft.application.authors.reduce(
        (sum, a) => sum + Number(a.contributionPercent || 0),
        0,
      );
    }
    if (mirrorsFromApplication && mirrorApplicationAuthors) {
      return mirrorApplicationAuthors.reduce(
        (sum, a) => sum + Number(a.contributionPercent || 0),
        0,
      );
    }
    return formData.participants.reduce((sum, p) => sum + (p.contributionPercent || 0), 0);
  }, [
    hasDraftContext,
    draft?.application.authors,
    formData.participants,
    mirrorsFromApplication,
    mirrorApplicationAuthors,
  ]);

  const isValid = totalPercent === 100;

  const contributionSignaturePrerequisiteGaps = useMemo(() => {
    if (!draftCtx || readOnly) return [];
    return collectContributionDigitalSignaturePrerequisiteGaps(
      draftCtx.draft.report,
      draftCtx.draft.application,
    );
  }, [draftCtx, readOnly, draft?.report, draft?.application]);

  /** Đồng bộ block tác giả chính với `authors[0]` khi bảng lấy từ tab Đơn (admin — không DraftProvider). */
  useEffect(() => {
    if (hasDraftContext) return;
    if (!mirrorsFromApplication || !mirrorApplicationAuthors) return;
    const a0 = mirrorApplicationAuthors[0];
    if (!a0) return;
    setFormData((prev) => {
      const mainAuthor = a0.name ?? '';
      const position = a0.workplace ?? '';
      const representativePercent = Number(a0.contributionPercent) || 0;
      if (
        prev.mainAuthor === mainAuthor &&
        prev.position === position &&
        prev.representativePercent === representativePercent
      ) {
        return prev;
      }
      return { ...prev, mainAuthor, position, representativePercent };
    });
  }, [hasDraftContext, mirrorsFromApplication, mirrorApplicationAuthors]);

  /** Tên sáng kiến từ tab Đơn (admin — không DraftProvider). */
  useEffect(() => {
    if (hasDraftContext) return;
    if (mirrorInitiativeNameFromApplicationProp === undefined) return;
    setFormData((prev) => {
      if (prev.initiativeName === mirrorInitiativeNameFromApplicationProp) return prev;
      return { ...prev, initiativeName: mirrorInitiativeNameFromApplicationProp };
    });
  }, [hasDraftContext, mirrorInitiativeNameFromApplicationProp]);

  // Sync main author as first participant (standalone / no draft only; skip when bảng lấy từ tab Đơn)
  useEffect(() => {
    if (hasDraftContext) return;
    if (mirrorsFromApplication) return;
    if (formData.mainAuthor && formData.participants.length === 0) {
      const newParticipant: Participant = {
        id: Date.now(),
        fullName: formData.mainAuthor,
        workUnit: formData.position,
        contributionPercent: formData.representativePercent,
        isEditing: false,
      };
      setFormData((prev) => ({
        ...prev,
        participants: [newParticipant],
      }));
    } else if (formData.participants.length > 0) {
      setFormData((prev) => ({
        ...prev,
        participants: prev.participants.map((p, index) =>
          index === 0
            ? {
                ...p,
                fullName: formData.mainAuthor,
                workUnit: formData.position,
                contributionPercent: formData.representativePercent,
              }
            : p,
        ),
      }));
    }
  }, [
    hasDraftContext,
    mirrorsFromApplication,
    formData.mainAuthor,
    formData.position,
    formData.representativePercent,
    formData.participants.length,
  ]);

  /** Keep header “tác giả chính” block aligned with Đơn `authors[0]` when the đơn table changes elsewhere. */
  useEffect(() => {
    if (!draft || readOnly) return;
    const a0 = draft.application.authors[0];
    if (!a0) return;
    setFormData((prev) => {
      const mainAuthor = a0.name ?? '';
      const position = a0.workplace ?? '';
      const representativePercent = Number(a0.contributionPercent) || 0;
      if (
        prev.mainAuthor === mainAuthor &&
        prev.position === position &&
        prev.representativePercent === representativePercent
      ) {
        return prev;
      }
      return { ...prev, mainAuthor, position, representativePercent };
    });
  }, [readOnly, draftId, applicationAuthors]);

  /**
   * “Tên sáng kiến” is the same field as báo cáo §2.1 and Đơn (`report.initiativeName` / `application.initiativeName`).
   * @see InitiativeReportForm initiative name input
   */
  const handleInitiativeNameChange = useCallback(
    (value: string) => {
      if (readOnly) return;
      if (mirrorsInitiativeNameFromApplication) return;
      setFormData((prev) => ({ ...prev, initiativeName: value }));
      const ctx = draftCtxRef.current;
      if (ctx && !readOnly) {
        ctx.updateReport({ initiativeName: value });
        void ctx.updateApplication({ initiativeName: value });
      }
    },
    [readOnly, mirrorsInitiativeNameFromApplication],
  );

  useEffect(() => {
    if (!draft || readOnly) return;
    const appName = draft.application.initiativeName ?? '';
    setFormData((prev) => {
      if (prev.initiativeName === appName) return prev;
      return { ...prev, initiativeName: appName };
    });
    const reportName = draft.report.initiativeName ?? '';
    if (reportName !== appName && updateReport) {
      updateReport({ initiativeName: appName });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- use draft primitives + stable updateReport; omit unstable context
  }, [readOnly, draftId, draft?.application.initiativeName, draft?.report.initiativeName, updateReport]);

  /**
   * Trùng với Mẫu 03 §2 và báo cáo §2.2 (`report.representativeAuthor`), Đơn tác giả thứ nhất.
   * @see InitiativeReportForm §2.2
   */
  const handleMainAuthorChange = useCallback(
    (value: string) => {
      if (readOnly) return;
      if (mirrorsFromApplication) return;
      setFormData((prev) => ({ ...prev, mainAuthor: value }));
      const ctx = draftCtxRef.current;
      if (ctx && !readOnly) {
        pushMainAuthorToDraft(ctx, value);
      }
    },
    [readOnly, mirrorsFromApplication],
  );

  useEffect(() => {
    if (readOnly) return;
    const ctx = draftCtxRef.current;
    if (!ctx) return;
    const canonical = canonicalMainAuthorFromDraft(ctx.draft);
    setFormData((prev) => {
      if (prev.mainAuthor === canonical) return prev;
      return { ...prev, mainAuthor: canonical };
    });
    reconcileRepresentativeAuthorSlices(ctx, readOnly);
  }, [
    readOnly,
    draftId,
    draft?.application.authors[0]?.name,
    draft?.report.representativeAuthor,
  ]);

  const patchFirstAuthorInDraft = useCallback(
    (patch: Partial<Pick<Author, 'name' | 'workplace' | 'contributionPercent'>>) => {
      const ctx = draftCtxRef.current;
      if (!ctx || readOnly) return;
      const authors = ctx.draft.application.authors;
      const first = authors[0];
      if (!first) return;
      void ctx.updateApplication({
        authors: [{ ...first, ...patch }, ...authors.slice(1)],
      });
    },
    [readOnly],
  );

  const handlePositionChange = useCallback(
    (value: string) => {
      if (readOnly) return;
      if (mirrorsFromApplication) return;
      setFormData((prev) => ({ ...prev, position: value }));
      patchFirstAuthorInDraft({ workplace: value });
    },
    [patchFirstAuthorInDraft, mirrorsFromApplication],
  );

  const handleRepresentativePercentChange = useCallback(
    (value: number) => {
      if (readOnly) return;
      if (mirrorsFromApplication) return;
      setFormData((prev) => ({ ...prev, representativePercent: value }));
      patchFirstAuthorInDraft({ contributionPercent: value });
    },
    [patchFirstAuthorInDraft, mirrorsFromApplication],
  );

  const handleInputChange = (field: keyof ContributionFormState, value: string | number | Date | boolean) => {
    if (readOnly) return;
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const addParticipant = () => {
    if (readOnly) return;
    if (mirrorsFromApplication) {
      toast.info('Thêm tác giả ở tab « Đơn Đề nghị Công nhận » (bảng đang đồng bộ với Đơn).');
      return;
    }
    if (draftCtx) {
      const newAuthor = createEmptyAuthorRow();
      const authors = [...draftCtx.draft.application.authors, newAuthor];
      void draftCtx.updateApplication({ authors });
      setEditingAuthorId(newAuthor.id);
      setAuthorEditBackup(null);
      return;
    }
    const newParticipant: Participant = {
      id: Date.now(),
      fullName: '',
      workUnit: '',
      contributionPercent: 0,
      isEditing: true,
    };
    setFormData((prev) => ({
      ...prev,
      participants: [...prev.participants, newParticipant],
    }));
    setEditingRow(newParticipant);
  };

  const updateParticipant = (id: number, field: keyof Participant, value: string | number | boolean) => {
    if (mirrorsFromApplication && !draftCtx) return;
    if (draftCtx && !readOnly) {
      const col =
        field === 'fullName' || field === 'workUnit' || field === 'contributionPercent' ? field : null;
      if (!col) return;
      const authorKey = contributionColumnToAuthorField(col);
      const authors = draftCtx.draft.application.authors.map((a) => {
        if (a.id !== id) return a;
        const v =
          authorKey === 'contributionPercent'
            ? normalizeContributionPercent(value)
            : value;
        return { ...a, [authorKey]: v };
      });
      void draftCtx.updateApplication({ authors });
      return;
    }
    setFormData((prev) => ({
      ...prev,
      participants: prev.participants.map((p) => (p.id === id ? { ...p, [field]: value } : p)),
    }));
  };

  const removeParticipant = (id: number) => {
    if (mirrorsFromApplication) {
      toast.info('Xóa hoặc chỉnh tác giả ở tab « Đơn Đề nghị Công nhận » (bảng đang đồng bộ với Đơn).');
      return;
    }
    if (tableParticipants[0]?.id === id) {
      toast.error('Không thể xóa tác giả chính');
      return;
    }
    if (draftCtx && !readOnly) {
      const authors = draftCtx.draft.application.authors.filter((a) => a.id !== id);
      void draftCtx.updateApplication({ authors });
      if (editingAuthorId === id) {
        setEditingAuthorId(null);
        setAuthorEditBackup(null);
      }
      return;
    }
    setFormData((prev) => ({
      ...prev,
      participants: prev.participants.filter((p) => p.id !== id),
    }));
  };

  const startEditing = (participant: Participant) => {
    if (readOnly) return;
    if (mirrorsFromApplication) {
      toast.info('Chỉnh tác giả ở tab « Đơn Đề nghị Công nhận » (bảng đang đồng bộ với Đơn).');
      return;
    }
    if (draftCtx) {
      const author = draftCtx.draft.application.authors.find((a) => a.id === participant.id);
      setAuthorEditBackup(author ? { ...author } : null);
      setEditingAuthorId(participant.id);
      return;
    }
    setEditingRow({ ...participant });
    updateParticipant(participant.id, 'isEditing', true);
  };

  const cancelEditing = (id: number) => {
    if (draftCtx && !readOnly) {
      if (authorEditBackup?.id === id) {
        void draftCtx.updateApplication({
          authors: draftCtx.draft.application.authors.map((a) => (a.id === id ? authorEditBackup : a)),
        });
      }
      if (editingAuthorId === id) {
        setEditingAuthorId(null);
        setAuthorEditBackup(null);
      }
      return;
    }
    if (editingRow) {
      setFormData((prev) => ({
        ...prev,
        participants: prev.participants.map((p) =>
          p.id === id ? { ...editingRow, isEditing: false } : p,
        ),
      }));
    }
    setEditingRow(null);
  };

  const saveEditing = (id: number) => {
    if (readOnly) return;
    if (draftCtx) {
      setEditingAuthorId(null);
      setAuthorEditBackup(null);
      return;
    }
    updateParticipant(id, 'isEditing', false);
    setEditingRow(null);
  };

  const handleSubmit = () => {
    if (!isValid) {
      toast.error('Tổng tỷ lệ đóng góp phải bằng 100%');
      return;
    }
    if (!formData.digitalSignatureConfirmed) {
      toast.error('Vui lòng xác nhận chữ ký số');
      return;
    }
    if (!formData.initiativeName.trim()) {
      toast.error('Vui lòng nhập tên sáng kiến');
      return;
    }
    if (!formData.mainAuthor.trim()) {
      toast.error('Vui lòng nhập tên tác giả chính');
      return;
    }
    toast.success('Đã lưu bản xác nhận thành công!');
  };

  return (
    <Card className="border-border shadow-lg">
      <div className="relative">
        <div className="text-center mt-6 space-y-1">
          <div className="flex justify-center gap-8 text-xs text-muted-foreground mb-4">
            <div>
              <p className="font-semibold">BỘ Y TẾ</p>
              <p className="font-bold text-foreground">ĐẠI HỌC Y DƯỢC</p>
              <p className="font-bold text-foreground">THÀNH PHỐ HỒ CHÍ MINH</p>
            </div>
            <div>
              <p className="font-semibold">CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</p>
              <p className="font-bold text-foreground">Độc lập – Tự do – Hạnh phúc</p>
            </div>
          </div>
          <CardTitle className="text-2xl font-bold uppercase">
            Bản Xác Nhận
          </CardTitle>
          <p className="text-lg font-semibold text-foreground">
            Tỷ Lệ (%) Đóng Góp Vào Việc Tạo Ra Sáng Kiến
          </p>
        </div>
      </div>

      <CardContent className="p-6 md:p-8 space-y-6">
        {/* Section 1: General Information */}
        <section className="space-y-4">
          <h2 className="text-lg font-bold text-foreground border-b border-border pb-2">
            Thông Tin Chung
          </h2>

          <div>
            <Label htmlFor="initiativeName" className="text-sm font-medium">
              1. Tên sáng kiến <span className="text-destructive">*</span>
            </Label>
            <Textarea
              id="initiativeName"
              placeholder="Nhập tên sáng kiến..."
              className="min-h-20 mt-1"
              value={formData.initiativeName}
              onChange={(e) => handleInitiativeNameChange(e.target.value)}
              disabled={readOnly || mirrorsInitiativeNameFromApplication}
            />
          </div>

          <div>
            <Label htmlFor="mainAuthor" className="text-sm font-medium">
              2. Tác giả chính / Đại diện nhóm tác giả sáng kiến <span className="text-destructive">*</span>
            </Label>
            <Input
              id="mainAuthor"
              placeholder="Nhập họ và tên..."
              className="mt-1"
              value={formData.mainAuthor}
              onChange={(e) => handleMainAuthorChange(e.target.value)}
              disabled={readOnly || mirrorsFromApplication}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="position" className="text-sm font-medium">
                Chức vụ, đơn vị công tác
              </Label>
              <Input
                id="position"
                placeholder="Nhập chức vụ và đơn vị..."
                className="mt-1"
                value={formData.position}
                onChange={(e) => handlePositionChange(e.target.value)}
                disabled={readOnly || mirrorsFromApplication}
              />
            </div>

            <div>
              <Label htmlFor="representativePercent" className="text-sm font-medium">
                Tỷ lệ đóng góp của đại diện (%)
              </Label>
              <Input
                id="representativePercent"
                type="number"
                min={0}
                max={100}
                placeholder="0"
                className="mt-1"
                value={formData.representativePercent || ''}
                onChange={(e) => handleRepresentativePercentChange(Number(e.target.value))}
                disabled={readOnly || mirrorsFromApplication}
              />
            </div>
          </div>

          <div>
            <Label className="text-sm font-medium">Ngày nộp</Label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  disabled={readOnly}
                  className={cn(
                    "w-full md:w-[280px] justify-start text-left font-normal mt-1",
                    !formData.submissionDate && "text-muted-foreground"
                  )}
                >
                  <CalendarIcon className="mr-2 h-4 w-4" />
                  {formData.submissionDate ? (
                    format(formData.submissionDate, 'dd/MM/yyyy')
                  ) : (
                    <span>Chọn ngày</span>
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                  mode="single"
                  selected={formData.submissionDate}
                  onSelect={(date) => date && handleInputChange('submissionDate', date)}
                  initialFocus
                  className="pointer-events-auto"
                />
              </PopoverContent>
            </Popover>
          </div>
        </section>

        {/* Section 2: Participant Table */}
        <section className="space-y-4">
          <div className="flex justify-between items-center">
            <h2 className="text-lg font-bold text-foreground border-b border-border pb-2 flex-1">
              Tỷ Lệ Đóng Góp
            </h2>
            <Button
              type="button"
              onClick={addParticipant}
              size="sm"
              className="gap-1"
              disabled={readOnly || mirrorsFromApplication}
            >
              <Plus size={16} /> Thêm thành viên
            </Button>
          </div>

          <div className="overflow-x-auto border border-border rounded-lg">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-16 text-center">STT</TableHead>
                  <TableHead>Họ và tên</TableHead>
                  <TableHead>Đơn vị công tác</TableHead>
                  <TableHead className="w-32 text-center">% đóng góp</TableHead>
                  <TableHead className="w-24 text-center">Thao tác</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {tableParticipants.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center text-muted-foreground italic py-8">
                      Nhập thông tin tác giả chính để bắt đầu
                    </TableCell>
                  </TableRow>
                )}
                {tableParticipants.map((participant, index) => (
                  <TableRow key={participant.id}>
                    <TableCell className="text-center font-medium">{index + 1}</TableCell>
                    <TableCell>
                      {participant.isEditing ? (
                        <Input
                          className="border-input"
                          value={participant.fullName}
                          onChange={(e) => updateParticipant(participant.id, 'fullName', e.target.value)}
                          disabled={index === 0 || readOnly || mirrorsFromApplication}
                        />
                      ) : (
                        <span>{participant.fullName || '-'}</span>
                      )}
                    </TableCell>
                    <TableCell>
                      {participant.isEditing ? (
                        <Input
                          className="border-input"
                          value={participant.workUnit}
                          onChange={(e) => updateParticipant(participant.id, 'workUnit', e.target.value)}
                          disabled={index === 0 || readOnly || mirrorsFromApplication}
                        />
                      ) : (
                        <span>{participant.workUnit || '-'}</span>
                      )}
                    </TableCell>
                    <TableCell className="text-center">
                      {participant.isEditing ? (
                        <Input
                          type="number"
                          min={0}
                          max={100}
                          className="border-input text-center w-20 mx-auto"
                          value={participant.contributionPercent || ''}
                          onChange={(e) => updateParticipant(participant.id, 'contributionPercent', Number(e.target.value))}
                          disabled={index === 0 || readOnly || mirrorsFromApplication}
                        />
                      ) : (
                        <span>{participant.contributionPercent}%</span>
                      )}
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex justify-center gap-1">
                        {index === 0 ? (
                          <span className="text-xs text-muted-foreground italic">Tác giả chính</span>
                        ) : readOnly || mirrorsFromApplication ? (
                          <span className="text-xs text-muted-foreground">—</span>
                        ) : participant.isEditing ? (
                          <>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => saveEditing(participant.id)}
                              className="h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-50"
                            >
                              <Check size={16} />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => cancelEditing(participant.id)}
                              className="h-8 w-8 text-muted-foreground hover:text-foreground"
                            >
                              <X size={16} />
                            </Button>
                          </>
                        ) : (
                          <>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => startEditing(participant)}
                              className="h-8 w-8 text-primary hover:text-primary hover:bg-primary/10"
                            >
                              <Pencil size={16} />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => removeParticipant(participant.id)}
                              className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
                            >
                              <Trash2 size={16} />
                            </Button>
                          </>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
              <TableFooter>
                <TableRow>
                  <TableCell colSpan={3} className="text-right font-bold">
                    TỔNG CỘNG
                  </TableCell>
                  <TableCell className={cn(
                    "text-center font-bold text-lg",
                    isValid ? "text-green-600" : "text-destructive"
                  )}>
                    {totalPercent}%
                  </TableCell>
                  <TableCell className="text-center">
                    {isValid ? (
                      <span className="text-green-600 text-xs">✓ Hợp lệ</span>
                    ) : (
                      <span className="text-destructive text-xs">Cần = 100%</span>
                    )}
                  </TableCell>
                </TableRow>
              </TableFooter>
            </Table>
          </div>

          {!isValid && tableParticipants.length > 0 && (
            <p className="text-sm text-destructive">
              ⚠️ Tổng tỷ lệ đóng góp phải bằng đúng 100% để có thể gửi biểu mẫu.
            </p>
          )}
        </section>

        {/* Section 3: Signature */}
        <section className="border-t border-border pt-6 space-y-6">
          <div className="flex items-center space-x-3">
            <Checkbox
              id="digitalSignature"
              checked={formData.digitalSignatureConfirmed}
              disabled={readOnly}
              onCheckedChange={(checked) => {
                if (readOnly) return;
                const v = !!checked;
                if (v && draftCtx && contributionSignaturePrerequisiteGaps.length > 0) {
                  toast.error('Chưa thể xác nhận cam kết', {
                    description: formatApplicantPrerequisiteToastDescription(
                      contributionSignaturePrerequisiteGaps,
                    ),
                  });
                  return;
                }
                handleInputChange('digitalSignatureConfirmed', v);
              }}
            />
            <Label htmlFor="digitalSignature" className="text-sm font-medium cursor-pointer">
              Tôi xin cam đoan mọi thông tin nêu trong đơn là trung thực, đúng sự thật và hoàn toàn chịu
              trách nhiệm trước pháp luật.
            </Label>
          </div>

          <div className="flex flex-col md:flex-row justify-between items-start gap-8">
            <div className="text-center w-full md:w-1/2">
              <p className="italic text-muted-foreground mb-2">
                TP. Hồ Chí Minh, {format(formData.submissionDate, 'dd/MM/yyyy')}
              </p>
              <p className="font-bold uppercase mb-16 text-foreground">
                Tác giả chính / Đại diện nhóm tác giả sáng kiến
              </p>
              <div className="border-t border-border w-48 mx-auto pt-2">
                <p className="text-sm text-muted-foreground">(chữ ký và ghi rõ họ tên)</p>
                {formData.digitalSignatureConfirmed && formData.mainAuthor && (
                  <p className="font-semibold text-primary mt-2">{formData.mainAuthor}</p>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* Action Buttons */}
        <div className="flex justify-end gap-4 border-t border-border pt-6">
          
          <Button 
            className="gap-2 shadow-lg" 
            type="button"
            onClick={() => void handleSaveDraft()}
            disabled={readOnly || !isValid || !formData.digitalSignatureConfirmed || isSavingDraft}
          >
            <Save size={18} /> {isSavingDraft ? 'Đang lưu...' : 'Tiếp theo'}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
