"use client";

import { useEffect, useMemo, useState, type ReactNode } from "react";
import type { ApplicationDetail } from "@/lib/types";
import { EDUCATION_OPTIONS, STATUS_LABELS } from "@/lib/labels";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Select, Textarea } from "@/components/ui/Field";
import { PersianDatePicker } from "@/components/ui/PersianDatePicker";

function asRecord(value: unknown): Record<string, unknown> {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : {};
}

function text(value: unknown): string {
  if (value == null || value === "") return "—";
  return String(value);
}

function genderLabel(gender: unknown) {
  if (gender === "male") return "پسر";
  if (gender === "female") return "دختر";
  return "—";
}

function formatDate(value?: string | null) {
  if (!value) return "—";
  const d = new Date(value.length <= 10 ? `${value}T12:00:00` : value);
  if (Number.isNaN(d.getTime())) return value;
  return d.toLocaleString("fa-IR");
}

function personName(person: Record<string, unknown>) {
  const first = String(person.first_name ?? "").trim();
  const last = String(person.last_name ?? "").trim();
  const name = `${first} ${last}`.trim();
  return name || "—";
}

function educationalValue(
  raw: unknown,
  field?: { type?: string; options?: Array<{ value: string; label: string }> },
): string {
  if (raw == null || raw === "") return "—";
  if (field?.type === "select" && field.options?.length) {
    const match = field.options.find((o) => o.value === String(raw));
    return match?.label ?? String(raw);
  }
  return String(raw);
}

function Section({ title, children }: { title: string; children: ReactNode }) {
  return (
    <section className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
      <h3 className="mb-3 text-sm font-bold">{title}</h3>
      {children}
    </section>
  );
}

function DefList({ rows }: { rows: Array<[string, string]> }) {
  return (
    <dl className="grid gap-2 sm:grid-cols-2">
      {rows.map(([label, value]) => (
        <div key={label} className="rounded-xl bg-slate-50 px-3 py-2 text-sm">
          <dt className="text-xs text-[var(--muted)]">{label}</dt>
          <dd className="mt-1 font-medium whitespace-pre-wrap">{value}</dd>
        </div>
      ))}
    </dl>
  );
}

type ParentDraft = {
  first_name: string;
  last_name: string;
  birth_year: string;
  education: string;
  field_of_study: string;
  job: string;
  work_phone: string;
  mobile: string;
  email: string;
};

function emptyParent(person: Record<string, unknown> = {}): ParentDraft {
  return {
    first_name: String(person.first_name ?? ""),
    last_name: String(person.last_name ?? ""),
    birth_year: String(person.birth_year ?? ""),
    education: String(person.education ?? ""),
    field_of_study: String(person.field_of_study ?? ""),
    job: String(person.job ?? ""),
    work_phone: String(person.work_phone ?? ""),
    mobile: String(person.mobile ?? ""),
    email: String(person.email ?? ""),
  };
}

export function ApplicationDetailView({
  detail,
  canEdit,
  saving,
  onSave,
  onReplaceDocument,
}: {
  detail: ApplicationDetail;
  canEdit: boolean;
  saving?: boolean;
  onSave: (formData: Record<string, unknown>) => Promise<void>;
  onReplaceDocument: (documentType: string, file: File) => Promise<void>;
}) {
  const form = asRecord(detail.form_data);
  const educational = asRecord(form.educational);
  const parents = asRecord(form.parents);
  const father = asRecord(parents.father);
  const mother = asRecord(parents.mother);
  const residence = asRecord(form.residence);
  const profile = detail.branch?.profile;

  const [editing, setEditing] = useState(false);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [studentMobile, setStudentMobile] = useState("");
  const [gender, setGender] = useState("");
  const [birthDate, setBirthDate] = useState("");
  const [fatherDraft, setFatherDraft] = useState<ParentDraft>(emptyParent());
  const [motherDraft, setMotherDraft] = useState<ParentDraft>(emptyParent());
  const [address, setAddress] = useState("");
  const [homePhone, setHomePhone] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [eduDraft, setEduDraft] = useState<Record<string, string>>({});

  useEffect(() => {
    setFirstName(String(form.first_name ?? ""));
    setLastName(String(form.last_name ?? ""));
    setStudentMobile(String(form.mobile ?? form.student_mobile ?? ""));
    setGender(String(form.gender ?? ""));
    setBirthDate(String(form.birth_date ?? ""));
    setFatherDraft(emptyParent(father));
    setMotherDraft(emptyParent(mother));
    setAddress(String(residence.address ?? ""));
    setHomePhone(String(residence.home_phone ?? ""));
    setPostalCode(String(residence.postal_code ?? ""));
    const nextEdu: Record<string, string> = {};
    for (const field of detail.educational_fields ?? []) {
      nextEdu[field.key] = String(educational[field.key] ?? "");
    }
    setEduDraft(nextEdu);
    setEditing(false);
  }, [detail.id, detail.form_data, detail.educational_fields]);

  const educationalRows = useMemo(() => {
    const fields = detail.educational_fields ?? [];
    if (fields.length) {
      return fields.map((field) => [field.label, educationalValue(educational[field.key], field)] as [string, string]);
    }
    return Object.entries(educational).map(([key, value]) => [key, text(value)] as [string, string]);
  }, [detail.educational_fields, educational]);

  const parentRows = (person: Record<string, unknown>): Array<[string, string]> => [
    ["نام", personName(person)],
    ["سال تولد", text(person.birth_year)],
    ["تحصیلات", text(person.education)],
    ["رشته", text(person.field_of_study)],
    ["شغل", text(person.job)],
    ["تلفن محل کار", text(person.work_phone)],
    ["موبایل", text(person.mobile)],
    ["ایمیل", text(person.email)],
  ];

  const save = async () => {
    await onSave({
      first_name: firstName,
      last_name: lastName,
      mobile: studentMobile,
      gender: gender || null,
      birth_date: birthDate || null,
      parents: { father: fatherDraft, mother: motherDraft },
      residence: { address, home_phone: homePhone, postal_code: postalCode },
      educational: eduDraft,
    });
    setEditing(false);
  };

  const requiredDocs = detail.required_documents ?? [];
  const documents = detail.documents ?? [];
  const docCards = requiredDocs.length
    ? requiredDocs.map((schema) => ({
        type: schema.type,
        label: schema.label,
        required: Boolean(schema.required),
        file: documents.find((d) => d.document_type === schema.type),
      }))
    : documents.map((file) => ({
        type: file.document_type,
        label: file.label || file.document_type,
        required: false,
        file,
      }));

  return (
    <div className="space-y-4">
      {canEdit ? (
        <div className="flex flex-wrap items-center justify-between gap-2">
          <p className="text-xs text-[var(--muted)]">
            اگر دانش‌آموز اطلاعات یا مدرک را اشتباه ثبت کرده، از اینجا اصلاح کنید.
          </p>
          {editing ? (
            <div className="flex gap-2">
              <Button variant="secondary" onClick={() => setEditing(false)} disabled={saving}>
                انصراف
              </Button>
              <Button onClick={() => void save()} loading={saving}>
                ذخیره تغییرات
              </Button>
            </div>
          ) : (
            <Button variant="secondary" onClick={() => setEditing(true)}>
              ویرایش اطلاعات
            </Button>
          )}
        </div>
      ) : (
        <Alert tone="info">پس از تبدیل به دانش‌آموز، اصلاح از پروفایل دانش‌آموز انجام می‌شود.</Alert>
      )}

      <Section title="اطلاعات پایه دانش‌آموز">
        {editing ? (
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="نام">
              <Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
            </Field>
            <Field label="نام خانوادگی">
              <Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
            </Field>
            <Field label="موبایل دانش‌آموز">
              <Input
                type="tel"
                value={studentMobile}
                onChange={(e) => setStudentMobile(e.target.value.replace(/\D/g, "").slice(0, 11))}
              />
            </Field>
            <Field label="جنسیت">
              <Select value={gender} onChange={(e) => setGender(e.target.value)}>
                <option value="">—</option>
                <option value="male">پسر</option>
                <option value="female">دختر</option>
              </Select>
            </Field>
            <Field label="تاریخ تولد">
              <PersianDatePicker value={birthDate} onChange={setBirthDate} />
            </Field>
          </div>
        ) : (
          <DefList
            rows={[
              ["نام و نام خانوادگی", `${text(form.first_name)} ${text(form.last_name)}`.replace(/\s+/g, " ").trim() || "—"],
              [detail.is_foreign_national ? "شناسه اتباع" : "کد ملی", text(detail.applicant_national_code)],
              ["موبایل دانش‌آموز", text(form.mobile ?? form.student_mobile)],
              ["جنسیت", genderLabel(form.gender)],
              ["تاریخ تولد", formatDate(String(form.birth_date ?? ""))],
              ["وضعیت", STATUS_LABELS[detail.status] ?? detail.status],
              ["رشته تحصیلی", text(detail.study_field?.name)],
              ["لیست انتظار", detail.queue_type === "waitlist" ? `بله${detail.waitlist_position ? ` (جایگاه ${detail.waitlist_position})` : ""}` : "خیر"],
              ["تاریخ ارسال", formatDate(detail.submitted_at)],
              ["کد رهگیری", text(detail.uuid)],
            ]}
          />
        )}
      </Section>

      <Section title="اطلاعات مدرسه">
        <DefList
          rows={[
            ["مدرسه", text(detail.branch?.name)],
            ["پایه", text(detail.grade_level?.name)],
            ["شهرستان", text(profile?.city)],
            ["تلفن", text(profile?.phone)],
            ["آدرس", text(profile?.address)],
            ["وب‌سایت", text(profile?.website)],
          ]}
        />
      </Section>

      <Section title="اطلاعات آموزشی">
        {editing && (detail.educational_fields?.length ?? 0) > 0 ? (
          <div className="grid gap-3 sm:grid-cols-2">
            {(detail.educational_fields ?? []).map((field) => (
              <Field key={field.key} label={field.label}>
                {field.type === "select" && field.options?.length ? (
                  <Select
                    value={eduDraft[field.key] ?? ""}
                    onChange={(e) => setEduDraft((prev) => ({ ...prev, [field.key]: e.target.value }))}
                  >
                    <option value="">—</option>
                    {field.options.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </Select>
                ) : (
                  <Input
                    value={eduDraft[field.key] ?? ""}
                    onChange={(e) => setEduDraft((prev) => ({ ...prev, [field.key]: e.target.value }))}
                  />
                )}
              </Field>
            ))}
          </div>
        ) : educationalRows.length ? (
          <DefList rows={educationalRows} />
        ) : (
          <p className="text-sm text-[var(--muted)]">اطلاعات آموزشی ثبت نشده است.</p>
        )}
      </Section>

      <div className="grid gap-4 lg:grid-cols-2">
        <Section title="اطلاعات پدر">
          {editing ? (
            <ParentFields value={fatherDraft} onChange={setFatherDraft} />
          ) : (
            <DefList rows={parentRows(father)} />
          )}
        </Section>
        <Section title="اطلاعات مادر">
          {editing ? (
            <ParentFields value={motherDraft} onChange={setMotherDraft} />
          ) : (
            <DefList rows={parentRows(mother)} />
          )}
        </Section>
      </div>

      <Section title="محل سکونت">
        {editing ? (
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <Field label="آدرس">
                <Textarea rows={2} value={address} onChange={(e) => setAddress(e.target.value)} />
              </Field>
            </div>
            <Field label="تلفن منزل">
              <Input value={homePhone} onChange={(e) => setHomePhone(e.target.value)} />
            </Field>
            <Field label="کد پستی">
              <Input value={postalCode} onChange={(e) => setPostalCode(e.target.value)} />
            </Field>
          </div>
        ) : (
          <DefList
            rows={[
              ["آدرس", text(residence.address)],
              ["تلفن منزل", text(residence.home_phone)],
              ["کد پستی", text(residence.postal_code)],
            ]}
          />
        )}
      </Section>

      <Section title="مدارک">
        {docCards.length ? (
          <ul className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
            {docCards.map((card) => {
              const href = card.file?.url;
              const downloadHref = card.file?.download_url ?? (href ? `${href}?download=1` : undefined);
              const image = Boolean(card.file?.is_image) || /\.(jpe?g|png|gif|webp|bmp)$/i.test(card.file?.original_name ?? "");
              return (
                <li key={card.type} className="rounded-xl border border-[var(--border)] bg-slate-50 p-3">
                  <p className="text-sm font-semibold">
                    {card.label}
                    {card.required ? " *" : ""}
                  </p>
                  {card.file && href && image ? (
                    <a href={href} target="_blank" rel="noopener noreferrer" className="mt-2 inline-block" title="مشاهده">
                      <img
                        src={href}
                        alt={card.file.original_name}
                        className="h-16 w-16 rounded-lg border border-[var(--border)] object-cover"
                      />
                    </a>
                  ) : (
                    <p className="mt-1 text-xs text-[var(--muted)]">{card.file?.original_name ?? "بارگذاری نشده"}</p>
                  )}
                  <div className="mt-2 flex flex-wrap gap-2 text-xs">
                    {href ? (
                      <a href={href} target="_blank" rel="noopener noreferrer" className="font-semibold text-primary underline">
                        مشاهده
                      </a>
                    ) : null}
                    {downloadHref ? (
                      <a href={downloadHref} className="font-semibold text-primary underline">
                        دانلود
                      </a>
                    ) : null}
                  </div>
                  {canEdit ? (
                    <label className="mt-3 block text-xs">
                      <span className="mb-1 block text-[var(--muted)]">جایگزینی فایل</span>
                      <input
                        type="file"
                        accept="image/*,.pdf"
                        disabled={saving}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          e.target.value = "";
                          if (file) void onReplaceDocument(card.type, file);
                        }}
                      />
                    </label>
                  ) : null}
                </li>
              );
            })}
          </ul>
        ) : (
          <p className="text-sm text-[var(--muted)]">مدرکی بارگذاری نشده است.</p>
        )}
      </Section>

      <Section title="پرداخت">
        {detail.payments?.length ? (
          <ul className="space-y-3">
            {detail.payments.map((pay) => {
              const card = pay.method === "card_to_card";
              const rows: Array<[string, string]> = [
                ["روش", pay.method_label ?? (card ? "کارت‌به‌کارت" : "درگاه آنلاین")],
                ["مبلغ", `${Number(pay.amount).toLocaleString("fa-IR")} ریال`],
              ];
              if (!card) {
                rows.push(["درگاه", pay.gateway_label ?? pay.gateway ?? "—"]);
              }
              if (pay.reference) {
                rows.push([card ? "شماره پیگیری" : "شماره تراکنش", pay.reference]);
              }
              if (!card && pay.order_id) {
                rows.push(["شناسه سفارش", pay.order_id]);
              }
              rows.push(["تاریخ", formatDate(pay.paid_at ?? pay.created_at)]);

              return (
                <li key={pay.id} className="rounded-xl border border-[var(--border)] bg-slate-50 p-3">
                  <DefList rows={rows} />
                  {card && pay.receipt_url ? (
                    <div className="mt-3">
                      <p className="mb-2 text-xs text-[var(--muted)]">رسید کارت‌به‌کارت</p>
                      {pay.receipt_is_image ? (
                        <a
                          href={pay.receipt_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-block"
                          title="مشاهده رسید"
                        >
                          <img
                            src={pay.receipt_url}
                            alt={pay.receipt_name ?? "رسید پرداخت"}
                            className="h-24 w-24 rounded-lg border border-[var(--border)] object-cover"
                          />
                        </a>
                      ) : (
                        <p className="text-xs text-[var(--muted)]">{pay.receipt_name ?? "فایل رسید"}</p>
                      )}
                      <div className="mt-2 flex flex-wrap gap-2 text-xs">
                        <a
                          href={pay.receipt_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="font-semibold text-primary underline"
                        >
                          مشاهده
                        </a>
                        {pay.receipt_download_url ? (
                          <a href={pay.receipt_download_url} className="font-semibold text-primary underline">
                            دانلود
                          </a>
                        ) : null}
                      </div>
                    </div>
                  ) : null}
                </li>
              );
            })}
          </ul>
        ) : (
          <p className="text-sm text-[var(--muted)]">پرداختی ثبت نشده است.</p>
        )}
      </Section>

      <Section title="ارزیابی‌ها">
        {detail.evaluations?.length ? (
          <ul className="space-y-2">
            {detail.evaluations.map((ev) => (
              <li key={ev.id} className="rounded-xl bg-slate-50 px-3 py-2 text-sm">
                <p className="font-medium">
                  {ev.step_type} · {ev.status}
                  {ev.score != null ? ` · امتیاز ${ev.score}` : ""}
                </p>
                {ev.notes ? <p className="mt-1 text-xs text-[var(--muted)]">{ev.notes}</p> : null}
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-sm text-[var(--muted)]">ارزیابی ثبت نشده است.</p>
        )}
      </Section>

      <Section title="تاریخچه وضعیت">
        {detail.status_logs?.length ? (
          <ul className="space-y-2">
            {detail.status_logs.map((log) => (
              <li key={log.id} className="rounded-xl bg-slate-50 px-3 py-2 text-sm">
                <p className="font-medium">
                  {STATUS_LABELS[log.to_status] ?? log.to_status}
                  <span className="mr-2 text-xs font-normal text-[var(--muted)]">
                    {formatDate(log.created_at)}
                  </span>
                </p>
                {log.note ? <p className="mt-1 text-xs text-[var(--muted)]">{log.note}</p> : null}
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-sm text-[var(--muted)]">تاریخچه‌ای ثبت نشده است.</p>
        )}
      </Section>
    </div>
  );
}

function ParentFields({
  value,
  onChange,
}: {
  value: ParentDraft;
  onChange: (next: ParentDraft) => void;
}) {
  const patch = (key: keyof ParentDraft, next: string) => onChange({ ...value, [key]: next });
  return (
    <div className="grid gap-3 sm:grid-cols-2">
      <Field label="نام">
        <Input value={value.first_name} onChange={(e) => patch("first_name", e.target.value)} />
      </Field>
      <Field label="نام خانوادگی">
        <Input value={value.last_name} onChange={(e) => patch("last_name", e.target.value)} />
      </Field>
      <Field label="سال تولد">
        <Input value={value.birth_year} onChange={(e) => patch("birth_year", e.target.value)} />
      </Field>
      <Field label="تحصیلات">
        <Select value={value.education} onChange={(e) => patch("education", e.target.value)}>
          <option value="">—</option>
          {EDUCATION_OPTIONS.map((option) => (
            <option key={option} value={option}>
              {option}
            </option>
          ))}
        </Select>
      </Field>
      <Field label="رشته">
        <Input value={value.field_of_study} onChange={(e) => patch("field_of_study", e.target.value)} />
      </Field>
      <Field label="شغل">
        <Input value={value.job} onChange={(e) => patch("job", e.target.value)} />
      </Field>
      <Field label="تلفن محل کار">
        <Input value={value.work_phone} onChange={(e) => patch("work_phone", e.target.value)} />
      </Field>
      <Field label="موبایل">
        <Input value={value.mobile} onChange={(e) => patch("mobile", e.target.value)} />
      </Field>
      <Field label="ایمیل">
        <Input value={value.email} onChange={(e) => patch("email", e.target.value)} />
      </Field>
    </div>
  );
}
