"use client";

import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState, useTransition, useEffect } from "react";
import {
  FileText,
  Clock,
  CheckCircle,
  AlertCircle,
  WalletCards,
  Tent,
  ReceiptText,
  Truck,
  MessageSquareText,
  Plus,
  Trash2,
  Save,
  Send,
} from "lucide-react";
import { leaderReportFormSchema, type LeaderReportFormValues } from "@/lib/validators/schemas";
import { saveLeaderReportDraft, submitLeaderReport } from "@/services/leader.service";
import { formatDateRange } from "@/lib/formatters/date";
import { formatCurrency } from "@/lib/formatters/currency";
import type { LeaderReport } from "@/types/leader";
import styles from "./LeaderReportComponents.module.css";

interface Props {
  token: string;
  report: LeaderReport;
  onTotalsChange?: (totals: { totalIncome: number; totalExpense: number; balance: number }) => void;
}

export default function LeaderReportMainCard({ token, report, onTotalsChange }: Props) {
  const [isSaving, startSaving] = useTransition();
  const [isSubmitting, startSubmitting] = useTransition();
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [confirmSubmit, setConfirmSubmit] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const { register, control, handleSubmit, watch } = useForm<LeaderReportFormValues>({
    resolver: zodResolver(leaderReportFormSchema),
    defaultValues: {
      reported_transfer_amount: report.reported_transfer_amount ?? 0,
      reported_cash_amount: report.reported_cash_amount ?? 0,
      rentals: (report.rentals || []).map((r) => ({
        item_name: r.item_name,
        quantity: r.quantity,
        unit_price: r.unit_price,
        notes: r.notes ?? undefined,
      })),
      expenses: (report.expenses || []).map((e) => ({
        expense_name: e.expense_name,
        quantity: e.quantity,
        unit_price: e.unit_price,
        notes: e.notes ?? undefined,
      })),
      logistics: (report.logistics || []).map((l) => ({
        item_name: l.item_name,
        quantity: l.quantity,
        unit_price: l.unit_price,
        notes: l.notes ?? undefined,
      })),
      notes: report.notes ?? "",
    },
  });

  const rentalArray = useFieldArray({ control, name: "rentals" });
  const expenseArray = useFieldArray({ control, name: "expenses" });
  const logisticArray = useFieldArray({ control, name: "logistics" });

  const watched = watch();

  const rentalTotal = (watched.rentals || []).reduce(
    (sum, r) => sum + (Number(r.unit_price) || 0) * (Number(r.quantity) || 0),
    0
  );
  const expenseTotal = (watched.expenses || []).reduce(
    (sum, e) => sum + (Number(e.unit_price) || 0) * (Number(e.quantity) || 0),
    0
  );
  const logisticTotal = (watched.logistics || []).reduce(
    (sum, l) => sum + (Number(l.unit_price) || 0) * (Number(l.quantity) || 0),
    0
  );

  const uangDiterimaTotal =
    (Number(watched.reported_cash_amount) || 0) + (Number(watched.reported_transfer_amount) || 0);

  // Mengikuti persis rumus CrewReportService::recalculateTotals() di backend
  const totalIncome =
    (Number(watched.reported_cash_amount) || 0) +
    (Number(watched.reported_transfer_amount) || 0) +
    rentalTotal;
  const totalExpense = expenseTotal + logisticTotal;
  const balance = totalIncome - totalExpense;

  useEffect(() => {
    onTotalsChange?.({ totalIncome, totalExpense, balance });
  }, [totalIncome, totalExpense, balance, onTotalsChange]);

  const buildPayload = (data: LeaderReportFormValues) => ({
    reported_transfer_amount: data.reported_transfer_amount,
    reported_cash_amount: data.reported_cash_amount,
    rentals: data.rentals,
    expenses: data.expenses,
    logistics: data.logistics,
    notes: data.notes,
  });

  const onSaveDraft = handleSubmit((data: LeaderReportFormValues) => {
    setMessage(null);
    startSaving(async () => {
      try {
        await saveLeaderReportDraft(token, buildPayload(data));
        setMessage({ type: "success", text: "Draft laporan berhasil disimpan." });
      } catch (err) {
        setMessage({
          type: "error",
          text: err instanceof Error ? err.message : "Gagal menyimpan draft.",
        });
      }
    });
  });

  const onSubmitReport = handleSubmit((data: LeaderReportFormValues) => {
    if (!confirmSubmit) {
      setConfirmSubmit(true);
      return;
    }
    setMessage(null);
    startSubmitting(async () => {
      try {
        await submitLeaderReport(token, buildPayload(data));
        setSubmitted(true);
      } catch (err) {
        setMessage({
          type: "error",
          text: err instanceof Error ? err.message : "Gagal mengirim laporan.",
        });
        setConfirmSubmit(false);
      }
    });
  });

  // Success view if just submitted
  if (submitted) {
    return (
      <div className={styles.successCard}>
        <CheckCircle size={44} className={styles.successIconLarge} aria-hidden />
        <h2 className={styles.successHeading}>Laporan Berhasil Dikirim</h2>
        <p className={styles.successSubtitle}>
          Terima kasih atas dedikasi dan kerja keras Anda dalam memimpin perjalanan ini. Laporan Anda
          telah tersimpan dengan aman di sistem operasional.
        </p>
      </div>
    );
  }

  // Subtitle line formatting
  const tripSummaryLine =
    report.trip.mountain && report.trip.start_date && report.trip.end_date
      ? `${report.trip.mountain} via ${report.trip.route || "Jalur Resmi"} · ${formatDateRange(
          report.trip.start_date,
          report.trip.end_date
        )}`
      : report.trip.mountain
      ? `${report.trip.mountain} via ${report.trip.route || "Jalur Resmi"}`
      : "Informasi detail perjalanan";

  // Status badge logic
  const renderStatusBadge = () => {
    if (report.status === "REVISION_REQUIRED") {
      return (
        <span className={`${styles.statusBadge} ${styles.statusRevision}`}>
          <AlertCircle size={13} aria-hidden />
          <span>Perlu Revisi</span>
        </span>
      );
    }
    if (report.status === "SUBMITTED" || report.status === "APPROVED") {
      return (
        <span className={`${styles.statusBadge} ${styles.statusSubmitted}`}>
          <CheckCircle size={13} aria-hidden />
          <span>{report.status_label || "Sudah Dikirim"}</span>
        </span>
      );
    }
    return (
      <span className={`${styles.statusBadge} ${styles.statusPending}`}>
        <Clock size={13} aria-hidden />
        <span>Menunggu Pengisian</span>
      </span>
    );
  };

  const notesLength = (watched.notes || "").length;

  return (
    <article className={styles.mainCard}>
      {/* Card Header */}
      <header className={styles.cardHeader}>
        <div className={styles.cardHeaderTitleGroup}>
          <div className={styles.cardHeaderIconBox}>
            <FileText size={22} aria-hidden />
          </div>
          <div>
            <h2 className={styles.cardHeaderTitle}>Informasi Trip</h2>
            <p className={styles.cardHeaderSubtitle}>
              Kode laporan: <strong>{report.report_code}</strong>
            </p>
          </div>
        </div>

        <div>{renderStatusBadge()}</div>
      </header>

      {/* Trip Summary Line */}
      <div className={styles.tripSummaryLine}>{tripSummaryLine}</div>

      {/* Revision Notice if applicable */}
      {report.status === "REVISION_REQUIRED" && report.review_notes && (
        <div className={`${styles.banner} ${styles.bannerError}`} role="alert">
          <AlertCircle size={16} aria-hidden />
          <div>
            <strong>Catatan Revisi dari Admin:</strong> {report.review_notes}
          </div>
        </div>
      )}

      {/* Readonly notice if not editable */}
      {!report.is_editable && (
        <div className={`${styles.banner} ${styles.bannerConfirm}`}>
          <AlertCircle size={16} aria-hidden />
          <div>
            Laporan ini berstatus <strong>{report.status_label}</strong> dan sudah dikunci sehingga tidak
            dapat diubah kembali.
          </div>
        </div>
      )}

      {/* Form Fields */}
      <form noValidate>
        {/* Card 1: Pemasukan */}
        <section className={styles.groupCard}>
          <h3 className={styles.groupCardHeading}>
            <WalletCards size={20} className={styles.sectionIcon} aria-hidden />
            <span>Pemasukan</span>
          </h3>

          {/* 1a. Uang Diterima Leader */}
          <div className={styles.subSection}>
            <h4 className={styles.subHeading}>Uang Diterima Leader</h4>

            <div className={styles.twoColumnGrid}>
              <div className={styles.formGroup}>
                <label htmlFor="reported-transfer-amount" className={styles.formLabel}>
                  Jumlah Transfer
                </label>
                <input
                  id="reported-transfer-amount"
                  type="number"
                  disabled={!report.is_editable}
                  className={styles.formInput}
                  placeholder="0"
                  {...register("reported_transfer_amount", { valueAsNumber: true })}
                />
              </div>

              <div className={styles.formGroup}>
                <label htmlFor="reported-cash-amount" className={styles.formLabel}>
                  Jumlah Tunai
                </label>
                <input
                  id="reported-cash-amount"
                  type="number"
                  disabled={!report.is_editable}
                  className={styles.formInput}
                  placeholder="0"
                  {...register("reported_cash_amount", { valueAsNumber: true })}
                />
              </div>
            </div>

            <div className={styles.subTotalRow}>
              <span>Total Uang Diterima Leader</span>
              <strong>{formatCurrency(uangDiterimaTotal)}</strong>
            </div>
          </div>

          {/* 1b. Sewa Perlengkapan */}
          <div className={styles.subSection}>
            <h4 className={styles.subHeading}>
              <Tent size={16} className={styles.sectionIcon} aria-hidden />
              <span>Sewa Perlengkapan</span>
            </h4>

          {rentalArray.fields.length > 0 && (
            <div className={styles.dynamicList}>
              {rentalArray.fields.map((field, idx) => (
                <div key={field.id} className={styles.dynamicRow}>
                  <div className={styles.formGroup} style={{ flex: 2 }}>
                    <label htmlFor={`rental-${idx}-name`} className={styles.formLabel}>
                      Nama Barang
                    </label>
                    <input
                      id={`rental-${idx}-name`}
                      type="text"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      placeholder="Contoh: Tenda Dome 4P"
                      {...register(`rentals.${idx}.item_name`)}
                    />
                  </div>
                  <div className={styles.formGroup} style={{ flex: 1 }}>
                    <label htmlFor={`rental-${idx}-qty`} className={styles.formLabel}>
                      Jumlah
                    </label>
                    <input
                      id={`rental-${idx}-qty`}
                      type="number"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      min={1}
                      {...register(`rentals.${idx}.quantity`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className={styles.formGroup} style={{ flex: 1 }}>
                    <label htmlFor={`rental-${idx}-price`} className={styles.formLabel}>
                      Harga Sewa
                    </label>
                    <input
                      id={`rental-${idx}-price`}
                      type="number"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      min={0}
                      {...register(`rentals.${idx}.unit_price`, { valueAsNumber: true })}
                    />
                  </div>
                  {report.is_editable && (
                    <button
                      type="button"
                      onClick={() => rentalArray.remove(idx)}
                      className={styles.removeRowBtn}
                      aria-label="Hapus baris sewa"
                    >
                      <Trash2 size={16} aria-hidden />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}

          {report.is_editable && (
            <button
              type="button"
              onClick={() => rentalArray.append({ item_name: "", quantity: 1, unit_price: 0 })}
              className={styles.dashedActionArea}
            >
              <span className={styles.dashedActionBtnText}>
                <Plus size={16} aria-hidden />
                <span>Tambah Sewa</span>
              </span>
              <span className={styles.dashedActionHelper}>Tambahkan penyewaan alat selama trip.</span>
            </button>
          )}

            <div className={styles.subTotalRow}>
              <span>Total Sewa Perlengkapan</span>
              <strong>{formatCurrency(rentalTotal)}</strong>
            </div>
          </div>
        </section>

        {/* Card 2: Pengeluaran */}
        <section className={styles.groupCard}>
          <h3 className={styles.groupCardHeading}>
            <ReceiptText size={20} className={styles.sectionIcon} aria-hidden />
            <span>Pengeluaran</span>
          </h3>

          {/* 2a. Pengeluaran */}
          <div className={styles.subSection}>
            <h4 className={styles.subHeading}>Pengeluaran</h4>

          {expenseArray.fields.length > 0 && (
            <div className={styles.dynamicList}>
              {expenseArray.fields.map((field, idx) => (
                <div key={field.id} className={styles.dynamicRow}>
                  <div className={styles.formGroup} style={{ flex: 2 }}>
                    <label htmlFor={`expense-${idx}-name`} className={styles.formLabel}>
                      Nama Pengeluaran
                    </label>
                    <input
                      id={`expense-${idx}-name`}
                      type="text"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      placeholder="Contoh: Simaksi / Tiket Masuk"
                      {...register(`expenses.${idx}.expense_name`)}
                    />
                  </div>
                  <div className={styles.formGroup} style={{ flex: 1 }}>
                    <label htmlFor={`expense-${idx}-qty`} className={styles.formLabel}>
                      Jumlah
                    </label>
                    <input
                      id={`expense-${idx}-qty`}
                      type="number"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      min={1}
                      {...register(`expenses.${idx}.quantity`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className={styles.formGroup} style={{ flex: 1 }}>
                    <label htmlFor={`expense-${idx}-price`} className={styles.formLabel}>
                      Harga (Rp)
                    </label>
                    <input
                      id={`expense-${idx}-price`}
                      type="number"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      min={0}
                      {...register(`expenses.${idx}.unit_price`, { valueAsNumber: true })}
                    />
                  </div>
                  {report.is_editable && (
                    <button
                      type="button"
                      onClick={() => expenseArray.remove(idx)}
                      className={styles.removeRowBtn}
                      aria-label="Hapus baris pengeluaran"
                    >
                      <Trash2 size={16} aria-hidden />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}

          {report.is_editable && (
            <button
              type="button"
              onClick={() => expenseArray.append({ expense_name: "", quantity: 1, unit_price: 0 })}
              className={styles.dashedActionArea}
            >
              <span className={styles.dashedActionBtnText}>
                <Plus size={16} aria-hidden />
                <span>Tambah Pengeluaran</span>
              </span>
              <span className={styles.dashedActionHelper}>
                Catat semua pengeluaran operasional selama trip.
              </span>
            </button>
          )}

            <div className={styles.subTotalRow}>
              <span>Total Pengeluaran</span>
              <strong>{formatCurrency(expenseTotal)}</strong>
            </div>
          </div>

          {/* 2b. Logistik */}
          <div className={styles.subSection}>
            <h4 className={styles.subHeading}>
              <Truck size={16} className={styles.sectionIcon} aria-hidden />
              <span>Logistik</span>
            </h4>

          {logisticArray.fields.length > 0 && (
            <div className={styles.dynamicList}>
              {logisticArray.fields.map((field, idx) => (
                <div key={field.id} className={styles.dynamicRow}>
                  <div className={styles.formGroup} style={{ flex: 2 }}>
                    <label htmlFor={`logistic-${idx}-name`} className={styles.formLabel}>
                      Nama Barang
                    </label>
                    <input
                      id={`logistic-${idx}-name`}
                      type="text"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      placeholder="Contoh: Bahan Masak / Gas Kaleng"
                      {...register(`logistics.${idx}.item_name`)}
                    />
                  </div>
                  <div className={styles.formGroup} style={{ flex: 1 }}>
                    <label htmlFor={`logistic-${idx}-qty`} className={styles.formLabel}>
                      Jumlah
                    </label>
                    <input
                      id={`logistic-${idx}-qty`}
                      type="number"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      min={1}
                      {...register(`logistics.${idx}.quantity`, { valueAsNumber: true })}
                    />
                  </div>
                  <div className={styles.formGroup} style={{ flex: 1 }}>
                    <label htmlFor={`logistic-${idx}-price`} className={styles.formLabel}>
                      Harga Satuan
                    </label>
                    <input
                      id={`logistic-${idx}-price`}
                      type="number"
                      disabled={!report.is_editable}
                      className={styles.formInput}
                      min={0}
                      {...register(`logistics.${idx}.unit_price`, { valueAsNumber: true })}
                    />
                  </div>
                  {report.is_editable && (
                    <button
                      type="button"
                      onClick={() => logisticArray.remove(idx)}
                      className={styles.removeRowBtn}
                      aria-label="Hapus baris logistik"
                    >
                      <Trash2 size={16} aria-hidden />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}

          {report.is_editable && (
            <button
              type="button"
              onClick={() => logisticArray.append({ item_name: "", quantity: 1, unit_price: 0 })}
              className={styles.dashedActionArea}
            >
              <span className={styles.dashedActionBtnText}>
                <Plus size={16} aria-hidden />
                <span>Tambah Logistik</span>
              </span>
              <span className={styles.dashedActionHelper}>
                Catat kebutuhan logistik seperti konsumsi, transport, dll.
              </span>
            </button>
          )}

            <div className={styles.subTotalRow}>
              <span>Total Logistik</span>
              <strong>{formatCurrency(logisticTotal)}</strong>
            </div>
          </div>
        </section>

        {/* Catatan */}
        <section className={styles.formSection}>
          <h3 className={styles.sectionHeading}>
            <MessageSquareText size={18} className={styles.sectionIcon} aria-hidden />
            <span>Catatan</span>
          </h3>

          <textarea
            className={styles.formTextarea}
            disabled={!report.is_editable}
            placeholder="Catatan tambahan mengenai trip..."
            maxLength={500}
            {...register("notes")}
          />
          <span className={styles.charCount}>{notesLength}/500</span>
        </section>

        {/* Notifications & Confirm Banners */}
        {message && (
          <div
            className={`${styles.banner} ${
              message.type === "error" ? styles.bannerError : styles.bannerSuccess
            }`}
            role="alert"
          >
            {message.type === "error" ? (
              <AlertCircle size={16} aria-hidden />
            ) : (
              <CheckCircle size={16} aria-hidden />
            )}
            <div>{message.text}</div>
          </div>
        )}

        {confirmSubmit && (
          <div className={`${styles.banner} ${styles.bannerConfirm}`} role="alert">
            <AlertCircle size={16} aria-hidden />
            <div>
              Laporan tidak dapat diubah kembali setelah dikirim. Klik &quot;Konfirmasi Kirim&quot; sekali
              lagi untuk mengirim.
            </div>
          </div>
        )}

        {/* Actions Bar */}
        {report.is_editable && (
          <div className={styles.actionsBar}>
            <button
              type="button"
              onClick={onSaveDraft}
              disabled={isSaving || isSubmitting}
              className={styles.btnDraft}
              id="leader-save-draft"
            >
              <Save size={16} aria-hidden />
              <span>{isSaving ? "Menyimpan..." : "Simpan Draft"}</span>
            </button>

            <button
              type="button"
              onClick={onSubmitReport}
              disabled={isSubmitting || isSaving}
              className={styles.btnSubmit}
              id="leader-submit-report"
            >
              <Send size={16} aria-hidden />
              <span>
                {isSubmitting
                  ? "Mengirim..."
                  : confirmSubmit
                  ? "Konfirmasi Kirim"
                  : "Kirim Laporan"}
              </span>
            </button>
          </div>
        )}
      </form>
    </article>
  );
}
