import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'sonner';
import { Save, Send } from 'lucide-react';

import {
  Alert,
  AlertDescription,
  Button,
  Card,
  CardContent,
  createProject,
  getProject,
  submitProject,
  updateProject,
  PROJECT_STATUS_LABEL,
  type ProjectStatus,
} from '@ump/shared';

import {
  buildInitial,
  collectMissing,
  schema,
  type FormValues,
  type MissingField,
  type RepeatableRow,
} from '../components/proposal/proposalSchema';
import { FieldList, Repeatable } from '../components/proposal/ProposalFormFields';

/** Thuyết minh đề tài — schema-driven form over researchApi. New/draft is editable; once
 * submitted/approved/rejected it renders read-only (approved redirects to the cockpit). */
export function ProposalFormPage() {
  const { id: routeId } = useParams();
  const navigate = useNavigate();
  const [projectId, setProjectId] = useState<string | null>(routeId ?? null);
  const [status, setStatus] = useState<ProjectStatus>('draft');
  const [values, setValues] = useState<FormValues>(buildInitial);
  const [errors, setErrors] = useState<Set<string>>(new Set());
  const [missing, setMissing] = useState<MissingField[]>([]);
  const [loading, setLoading] = useState<boolean>(!!routeId);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!routeId) return;
    let cancelled = false;
    setLoading(true);
    getProject(routeId)
      .then((p) => {
        if (cancelled) return;
        if (p.status === 'approved') {
          navigate(`/dashboard/projects/${p.id}`, { replace: true });
          return;
        }
        setProjectId(p.id);
        setStatus(p.status);
        setValues({ ...buildInitial(), ...(p.content as FormValues) });
      })
      .catch(() => toast.error('Không tải được đề tài.'))
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [routeId, navigate]);

  const readOnly = status !== 'draft';
  const setValue = (k: string, v: string | string[]) => setValues((p) => ({ ...p, [k]: v }));
  const setRows = (k: string, rows: RepeatableRow[]) => setValues((p) => ({ ...p, [k]: rows }));

  const persist = async (): Promise<string> => {
    if (projectId) {
      await updateProject(projectId, values);
      return projectId;
    }
    const created = await createProject(values);
    setProjectId(created.id);
    window.history.replaceState(null, '', `/dashboard/proposals/${created.id}`);
    return created.id;
  };

  const onSaveDraft = async () => {
    setSaving(true);
    try {
      await persist();
      toast.success('Đã lưu bản thảo.');
    } catch {
      toast.error('Lưu bản thảo thất bại.');
    } finally {
      setSaving(false);
    }
  };

  const onSubmit = async () => {
    const miss = collectMissing(values);
    setErrors(new Set(miss.map((m) => m.key)));
    setMissing(miss);
    if (miss.length > 0) {
      toast.error(`Còn ${miss.length} trường bắt buộc chưa nhập.`);
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    setSaving(true);
    try {
      const pid = await persist();
      await submitProject(pid);
      toast.success('Đã nộp đề tài. Vui lòng chờ phê duyệt.');
      navigate('/dashboard/projects');
    } catch {
      toast.error('Nộp đề tài thất bại.');
    } finally {
      setSaving(false);
    }
  };

  const subtitleVal = values[schema.meta.subtitleField];
  const subtitle = subtitleVal ? ` CẤP ${String(subtitleVal).toUpperCase()}` : ' CẤP ...';

  const actions = (
    <div className="flex flex-wrap gap-2">
      <Button onClick={onSaveDraft} variant="outline" disabled={saving}>
        <Save className="mr-2 h-4 w-4" /> Lưu bản thảo
      </Button>
      <Button onClick={onSubmit} disabled={saving}>
        <Send className="mr-2 h-4 w-4" /> Nộp đề tài
      </Button>
    </div>
  );

  if (loading) return <div className="p-6 text-sm text-muted-foreground">Đang tải…</div>;

  return (
    <div className="mx-auto max-w-4xl space-y-5">
      <Card>
        <CardContent className="space-y-1 py-5 text-center">
          <div className="text-xs text-muted-foreground">{schema.meta.formCode}</div>
          <h1 className="font-serif text-xl font-bold tracking-wide text-foreground">
            {schema.meta.title}
            {subtitle}
          </h1>
          <div className="text-xs text-muted-foreground">{schema.meta.circular}</div>
        </CardContent>
      </Card>

      {readOnly && (
        <Alert>
          <AlertDescription>
            Đề tài đang ở trạng thái “{PROJECT_STATUS_LABEL[status]}” — chỉ xem, không thể chỉnh sửa.
          </AlertDescription>
        </Alert>
      )}

      {!readOnly && actions}

      {missing.length > 0 && (
        <Alert variant="destructive">
          <AlertDescription>
            <strong>Còn {missing.length} trường bắt buộc chưa nhập:</strong>
            <ul className="mt-2 list-disc pl-5">
              {missing.map((m) => (
                <li key={m.key}>{m.label}</li>
              ))}
            </ul>
          </AlertDescription>
        </Alert>
      )}

      {schema.topFields.length > 0 && (
        <Card>
          <CardContent className="py-5">
            <fieldset disabled={readOnly}>
              <FieldList fields={schema.topFields} values={values} errors={errors} onChange={setValue} />
            </fieldset>
          </CardContent>
        </Card>
      )}

      {schema.sections.map((s) => (
        <Card key={s.id} id={`sec-${s.id}`}>
          <CardContent className="py-5">
            <h2 className="mb-4 flex gap-2 border-b-2 border-primary pb-2.5 text-base font-bold text-foreground">
              <span className="text-primary">{s.id}.</span>
              <span>{s.title}</span>
            </h2>
            <fieldset disabled={readOnly}>
              <FieldList fields={s.fields} values={values} errors={errors} onChange={setValue} />
              {s.subsections?.map((sub) => (
                <div key={sub.id} className="mt-5 border-t border-dashed border-border pt-4">
                  <h3 className="mb-3 text-sm font-semibold">{sub.title}</h3>
                  <FieldList
                    fields={sub.fields}
                    prefix={sub.keyPrefix}
                    values={values}
                    errors={errors}
                    onChange={setValue}
                  />
                </div>
              ))}
              {s.repeatables?.map((rep) => (
                <Repeatable
                  key={rep.key}
                  rep={rep}
                  rows={(values[rep.key] as RepeatableRow[]) ?? []}
                  onRows={setRows}
                />
              ))}
            </fieldset>
          </CardContent>
        </Card>
      ))}

      <Card>
        <CardContent className="py-5">
          <h2 className="mb-4 flex gap-2 border-b-2 border-primary pb-2.5 text-base font-bold text-foreground">
            <span className="text-primary">Ký</span>
            <span>Xác nhận và chữ ký</span>
          </h2>
          <fieldset disabled={readOnly}>
            <FieldList
              fields={Object.values(schema.signature)}
              values={values}
              errors={errors}
              onChange={setValue}
            />
          </fieldset>
        </CardContent>
      </Card>

      {!readOnly && <div className="flex flex-wrap justify-end gap-2 pb-8">{actions}</div>}
    </div>
  );
}
