import { useState } from 'react';
import { Link, useForm } from '@inertiajs/react';
import AppLayout from '@/Layouts/AppLayout';
import { Button } from '@/Components/ui/button';
import {
    Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from '@/Components/ui/dialog';
import { RebateHeaderCard } from '@/Components/MenuCompanies/CompanyRebate/RebateHeaderCard';
import { RebateDetailTable } from '@/Components/MenuCompanies/CompanyRebate/RebateDetailTable';
import { CancelRebateButton } from '@/Components/MenuCompanies/CompanyRebate/CancelRebateButton';
import { GeneratedInvoicesPanel } from '@/Components/MenuCompanies/CompanyRebate/GeneratedInvoicesPanel';
import { useToast } from '@/Components/Toast';

/**
 * View All Detail — legacy companyrebatedetailall.php.
 * Cancel + Revise + Re-create + Change Validity, plus the two admin capabilities the legacy
 * page carried and this port was missing: Change Status (btn_changestatus) and Update
 * Recipient snapshot (btn_update).
 * Back link → /company-rebates/view-all
 */
export default function ViewAllDetail({ rebate, details, history, pageTitle, options, statusOptions = [], generatedInvoices = [] }) {
    const { show: showToast } = useToast();
    const changeValidityForm = useForm({
        validityDateStart: rebate.validityDateStart || '',
        validityDateEnd: rebate.validityDateEnd || '',
    });

    // Both dates are ISO (yyyy-mm-dd) from <input type="date">, so a string compare is a date compare.
    const { validityDateStart, validityDateEnd } = changeValidityForm.data;
    const invalidRange = Boolean(validityDateStart && validityDateEnd && validityDateEnd < validityDateStart);
    const validityError = changeValidityForm.errors.validityDateEnd || changeValidityForm.errors.validityDateStart;

    // ── Change Status (legacy btn_changestatus) ────────────────────────────
    const [lineDecisions, setLineDecisions] = useState(details);
    const [statusConfirm, setStatusConfirm] = useState(false);
    const changeStatusForm = useForm({
        statusId: rebate.statusId ?? '',
        remark: '',
        items: [],
    });

    const submitChangeStatus = () => {
        // transform, NOT setData-then-post: setData only lands on the next render, so the
        // decisions the admin just picked would be dropped. Same trap as the approval pages.
        changeStatusForm.transform((data) => ({
            ...data,
            items: lineDecisions.map((row) => ({ id: row.id, isRejected: !!row.isRejected })),
        }));
        changeStatusForm.post(route('company-rebates.change-status', { rebate: rebate.id }), {
            onSuccess: () => setStatusConfirm(false),
            onError: () => setStatusConfirm(false),
        });
    };

    // ── Refresh Recipients (legacy btn_update) ─────────────────────────────
    const [selectedCpIds, setSelectedCpIds] = useState([]);
    const [refreshConfirm, setRefreshConfirm] = useState(false);
    const refreshForm = useForm({ companyCpIds: [] });

    const toggleCp = (cpId) => setSelectedCpIds((prev) => (
        prev.includes(cpId) ? prev.filter((id) => id !== cpId) : [...prev, cpId]
    ));

    const submitRefresh = () => {
        refreshForm.transform((data) => ({ ...data, companyCpIds: selectedCpIds }));
        refreshForm.post(route('company-rebates.refresh-recipients', { rebate: rebate.id }), {
            onSuccess: () => { setRefreshConfirm(false); setSelectedCpIds([]); },
            onError: () => setRefreshConfirm(false),
        });
    };

    const canEditLines = options.changeStatusEnabled || options.refreshRecipientsEnabled;

    return (
        <div className="space-y-6">
            <RebateHeaderCard
                rebate={rebate}
                history={history}
                scope="view-all"
                pageTitle={pageTitle}
                options={options}
            />

            {/* Change Validity */}
            {options.changeValidityEnabled && (
                <div className="rounded-xl border border-border bg-card px-4 pt-3.5 pb-3 shadow-sm">
                    <p className="m-0 mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground">
                        Change Validity
                    </p>
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            changeValidityForm.post(route('company-rebates.change-validity', { rebate: rebate.id }), {
                                onError: () => showToast('Please check the form and try again.', 'error'),
                            });
                        }}
                        className="flex flex-wrap items-end gap-4"
                    >
                        <div className="flex items-center gap-2">
                            <label className="text-[13px] text-muted-foreground">Start:</label>
                            <input
                                type="date"
                                value={changeValidityForm.data.validityDateStart}
                                onChange={(e) => changeValidityForm.setData('validityDateStart', e.target.value)}
                                className="rounded border border-input bg-card px-3 py-1.5 text-[13px]"
                                required
                            />
                        </div>
                        <div className="flex items-center gap-2">
                            <label className="text-[13px] text-muted-foreground">End:</label>
                            <input
                                type="date"
                                value={changeValidityForm.data.validityDateEnd}
                                onChange={(e) => changeValidityForm.setData('validityDateEnd', e.target.value)}
                                className="rounded border border-input bg-card px-3 py-1.5 text-[13px]"
                                required
                            />
                        </div>
                        <Button type="submit" size="sm" disabled={changeValidityForm.processing || invalidRange}>
                            Change
                        </Button>
                    </form>

                    {/* The server enforces End >= Start (after_or_equal). Without this the 422 came
                        back invisible and the form just looked like it had done nothing. */}
                    {(invalidRange || validityError) && (
                        <p className="m-0 mt-2 text-[12px] font-semibold text-danger-text">
                            {invalidRange ? 'End date must be on or after the start date.' : validityError}
                        </p>
                    )}
                </div>
            )}

            {/* Detail table */}
            <div>
                <div className="mb-3 flex flex-wrap items-center gap-3">
                    <h3 className="m-0 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
                        Company Rebate Resume Details
                    </h3>
                    {options.refreshRecipientsEnabled && (
                        <div className="ml-auto flex items-center gap-3">
                            <span className="text-[11px] text-muted-foreground">
                                Centang kolom <strong>CP</strong> untuk menyegarkan data Recipient dari
                                Company CP.
                            </span>
                            <Button
                                size="sm"
                                variant="outline"
                                disabled={selectedCpIds.length === 0 || refreshForm.processing}
                                onClick={() => setRefreshConfirm(true)}
                            >
                                Update Recipient{selectedCpIds.length > 0 ? ` (${selectedCpIds.length})` : ''}
                            </Button>
                        </div>
                    )}
                </div>
                <RebateDetailTable
                    validityStart={rebate.validityDateStart}
                    validityEnd={rebate.validityDateEnd}
                    items={canEditLines ? lineDecisions : details}
                    mode={canEditLines ? 'edit-status' : 'readonly'}
                    statusId={rebate.statusId}
                    usdRate={rebate.usdRate}
                    onUpdate={setLineDecisions}
                    selectedCpIds={selectedCpIds}
                    onToggleCp={toggleCp}
                />
                {refreshForm.errors.companyCpIds && (
                    <p className="m-0 mt-2 text-[12px] font-semibold text-danger-text">
                        {refreshForm.errors.companyCpIds}
                    </p>
                )}
            </div>

            {/* Invoice section — legacy companyrebateinvoicelink.php */}
            {options.showInvoice && <GeneratedInvoicesPanel invoices={generatedInvoices} />}

            {/* Change Status (legacy btn_changestatus) */}
            {options.changeStatusEnabled && (
                <div className="rounded-xl border border-border bg-card px-4 pt-3.5 pb-3 shadow-sm">
                    <p className="m-0 mb-1 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground">
                        Change Status
                    </p>
                    <p className="m-0 mb-3 text-[11px] text-muted-foreground">
                        Memaksa status rebate beserta keputusan Accept/Reject tiap baris di tabel di
                        atas. Remark wajib diisi dan tercatat di history.
                    </p>
                    <div className="flex flex-wrap items-end gap-3">
                        <div className="flex items-center gap-2">
                            <label className="text-[13px] text-muted-foreground" htmlFor="cr-status">Status:</label>
                            <select
                                id="cr-status"
                                className="rounded border border-input bg-card px-3 py-1.5 text-[13px]"
                                value={changeStatusForm.data.statusId}
                                onChange={(e) => changeStatusForm.setData('statusId', e.target.value)}
                            >
                                <option value="">Select Status</option>
                                {statusOptions.map((s) => (
                                    <option key={s.id} value={s.id}>{s.name}</option>
                                ))}
                            </select>
                        </div>
                        <div className="flex min-w-[260px] flex-1 items-center gap-2">
                            <label className="text-[13px] text-muted-foreground" htmlFor="cr-status-remark">Remark:</label>
                            <input
                                id="cr-status-remark"
                                type="text"
                                autoComplete="off"
                                placeholder="Alasan perubahan status"
                                className="w-full rounded border border-input bg-card px-3 py-1.5 text-[13px]"
                                value={changeStatusForm.data.remark}
                                onChange={(e) => changeStatusForm.setData('remark', e.target.value)}
                            />
                        </div>
                        <Button
                            size="sm"
                            disabled={changeStatusForm.processing}
                            onClick={() => setStatusConfirm(true)}
                        >
                            Submit
                        </Button>
                    </div>
                    {(changeStatusForm.errors.statusId || changeStatusForm.errors.remark) && (
                        <p className="m-0 mt-2 text-[12px] font-semibold text-danger-text">
                            {changeStatusForm.errors.statusId || changeStatusForm.errors.remark}
                        </p>
                    )}
                </div>
            )}

            {/* Action buttons — left-aligned, primary first (locked UI ruling) */}
            <div className="flex flex-wrap items-center gap-3">
                {options.reviseEnabled && (
                    <Button asChild variant="outline">
                        <Link href={route('company-rebates.revise.show', { rebate: rebate.id })}>Revise</Link>
                    </Button>
                )}
                {options.recreateEnabled && (
                    <Button asChild variant="outline">
                        <Link href={route('company-rebates.recreate', { rebate: rebate.id })}>Re-create</Link>
                    </Button>
                )}
                {options.cancelEnabled && (
                    <CancelRebateButton rebateId={rebate.id} scope="view-all" />
                )}
            </div>

            {/* Change Status confirmation */}
            <Dialog open={statusConfirm} onOpenChange={setStatusConfirm}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Yakin untuk mengubah Status?</DialogTitle>
                        <DialogDescription>
                            Status rebate #{rebate.id} akan dipaksa ke pilihan Anda, di luar alur
                            approval normal, dan keputusan Accept/Reject tiap baris ikut disimpan.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setStatusConfirm(false)} disabled={changeStatusForm.processing}>
                            Batal
                        </Button>
                        <Button variant="destructive" onClick={submitChangeStatus} disabled={changeStatusForm.processing}>
                            {changeStatusForm.processing ? 'Memproses…' : 'Ubah Status'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Refresh Recipients confirmation — spells out the global reach */}
            <Dialog open={refreshConfirm} onOpenChange={setRefreshConfirm}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Update data Recipient?</DialogTitle>
                        <DialogDescription>
                            {selectedCpIds.length} contact akan disegarkan dari data Company CP terkini.
                            ⚠️ Perubahan berlaku pada <strong>SEMUA</strong> Company Rebate yang memakai
                            contact tersebut — bukan hanya rebate #{rebate.id} — termasuk yang sudah
                            disetujui.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setRefreshConfirm(false)} disabled={refreshForm.processing}>
                            Batal
                        </Button>
                        <Button variant="destructive" onClick={submitRefresh} disabled={refreshForm.processing}>
                            {refreshForm.processing ? 'Memproses…' : 'Ya, Update Recipient'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}

ViewAllDetail.layout = [AppLayout];
