"use client";

import React, { FormEvent, useContext, useState } from "react";
import Image from "next/image";

import { AxiosContext } from "@/providers/axios/axios-provider";
import PaginatedTable from "@/components/Tables/PaginatedTable/PaginatedTable";

import GetFinancialAdministrationsQuery, {
    FinancialAdministrationsQueryParamsType,
} from "@/api-queries/financial-administrations/get-financial-administrations-query";

import CreateFinancialAdministrationQuery, {
    CreateFinancialAdministrationQueryDataType,
} from "@/api-queries/financial-administrations/create-financial-administration-query";

import UpdateFinancialAdministrationQuery from "@/api-queries/financial-administrations/update-financial-administration-query";
import DeleteFinancialAdministrationQuery from "@/api-queries/financial-administrations/delete-financial-administration-query";
import FinancialAdministrationType from "@/api-queries/financial-administrations/financial-administration-type";
import { isValidIBAN } from "ibantools";

type FormDataType = CreateFinancialAdministrationQueryDataType;

const emptyForm: FormDataType = {
    name: "",
    secondary_name: "",
    address: "",
    fiscal_code: "",
    phone: "",
    bank_account: "",
};

const fields: {
    key: keyof FormDataType;
    label: string;
    required: boolean;
}[] = [
    {
        key: "name",
        label: "Denumire 1",
        required: true,
    },
    {
        key: "secondary_name",
        label: "Denumire 2",
        required: true,
    },
    {
        key: "address",
        label: "Adresă",
        required: true,
    },
    {
        key: "fiscal_code",
        label: "Cod fiscal",
        required: true,
    },
    {
        key: "phone",
        label: "Telefon",
        required: false,
    },
    {
        key: "bank_account",
        label: "Cont bancar",
        required: true,
    },
];

const FinancialAdministrations = () => {
    const axios = useContext(AxiosContext);

    const [forceRefresh, setForceRefresh] = useState<number>(0);
    const [saving, setSaving] = useState<boolean>(false);
    const [deletingId, setDeletingId] = useState<number | null>(null);

    const [showForm, setShowForm] = useState<boolean>(false);
    const [editingId, setEditingId] = useState<number | null>(null);

    const [form, setForm] = useState<FormDataType>({
        ...emptyForm,
    });

    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);

    const openCreate = () => {
        setEditingId(null);
        setForm({ ...emptyForm });
        setError(null);
        setSuccess(null);
        setShowForm(true);
    };

    const openEdit = (item: FinancialAdministrationType) => {
        setEditingId(item.id);

        setForm({
            name: item.name,
            secondary_name: item.secondary_name,
            address: item.address,
            fiscal_code: item.fiscal_code,
            phone: item.phone ?? "",
            bank_account: item.bank_account,
        });

        setError(null);
        setSuccess(null);
        setShowForm(true);
    };

    const closeForm = () => {
        setShowForm(false);
        setEditingId(null);
        setForm({ ...emptyForm });
    };

    const handleChange = (
        key: keyof FormDataType,
        value: string
    ) => {
        setForm((previous) => ({
            ...previous,
            [key]:
                key === "bank_account"
                    ? value.toUpperCase()
                    : value,
        }));
    };

    const handleSave = async (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        if (saving) {
            return;
        }
        const iban = form.bank_account.replace(/\s+/g, "").toUpperCase();
        if (!isValidIBAN(iban)) {
            setError("Contul IBAN introdus nu este valid.");
            return;
        }

        setSaving(true);
        setError(null);
        setSuccess(null);

        const wasEditing = editingId !== null;

        const payload: FormDataType = {
            name: form.name.trim(),
            secondary_name: form.secondary_name.trim(),
            address: form.address.trim(),
            fiscal_code: form.fiscal_code.trim(),
            phone: form.phone?.trim() || null,
            bank_account: iban,
        };

        try {
            if (editingId !== null) {
                await new UpdateFinancialAdministrationQuery(axios).execute({
                    id: editingId,
                    data: payload,
                });
            } else {
                await new CreateFinancialAdministrationQuery(axios).execute(
                    payload
                );
            }

            closeForm();

            setForceRefresh(Date.now());

            setSuccess(
                wasEditing
                    ? "Administrația financiară a fost actualizată."
                    : "Administrația financiară a fost adăugată."
            );
        } catch (err: unknown) {
            const response = (
                err as {
                    response?: {
                        data?: {
                            message?: string;
                            errors?: Record<string, string[]>;
                        };
                    };
                }
            )?.response;

            const firstValidationError = response?.data?.errors
                ? Object.values(response.data.errors).flat()[0]
                : undefined;

            setError(
                firstValidationError ||
                response?.data?.message ||
                "Nu s-a putut salva administrația financiară."
            );
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id: number) => {
        if (deletingId !== null) {
            return;
        }

        setDeletingId(id);
        setError(null);
        setSuccess(null);

        try {
            await new DeleteFinancialAdministrationQuery(axios).execute({
                id,
            });

            setForceRefresh(Date.now());

            if (editingId === id) {
                closeForm();
            }

            setSuccess("Administrația financiară a fost ștearsă.");
        } catch {
            setError("Nu s-a putut șterge administrația financiară.");
        } finally {
            setDeletingId(null);
        }
    };

    return (
        <section className="mt-8 rounded-lg border border-gray-200 bg-white p-6">
            <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
                <h3 className="text-xl font-semibold text-gray-900">
                    Administrații financiare
                </h3>

                <button
                    type="button"
                    onClick={openCreate}
                    className="rounded-lg bg-dark-orange px-5 py-2.5 text-sm font-medium text-white"
                >
                    + Adaugă administrație
                </button>
            </div>

            {error && (
                <div className="mb-4 rounded-lg bg-red-50 p-3 text-sm text-red-700">
                    {error}
                </div>
            )}

            {success && (
                <div className="mb-4 rounded-lg bg-green-50 p-3 text-sm text-green-700">
                    {success}
                </div>
            )}

            {showForm && (
                <form
                    onSubmit={handleSave}
                    className="mb-6 rounded-lg border border-gray-200 bg-gray-50 p-5"
                >
                    <h4 className="mb-5 text-lg font-semibold text-gray-900">
                        {editingId !== null
                            ? "Editează administrația financiară"
                            : "Adaugă administrație financiară"}
                    </h4>

                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                        {fields.map((field) => (
                            <div key={field.key}>
                                <label
                                    htmlFor={`financial-${field.key}`}
                                    className="mb-2 block text-sm font-medium text-gray-700"
                                >
                                    {field.label}
                                </label>

                                {field.key === "address" ? (
                                    <textarea
                                        id={`financial-${field.key}`}
                                        required={field.required}
                                        value={form.address}
                                        onChange={(event) =>
                                            handleChange(
                                                field.key,
                                                event.target.value
                                            )
                                        }
                                        rows={3}
                                        className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
                                    />
                                ) : (
                                    <input
                                        id={`financial-${field.key}`}
                                        type="text"
                                        required={field.required}
                                        maxLength={
                                            field.key === "fiscal_code" ||
                                            field.key === "phone"
                                                ? 32
                                                : field.key === "bank_account"
                                                    ? 64
                                                    : 255
                                        }
                                        value={form[field.key] ?? ""}
                                        onChange={(event) =>
                                            handleChange(
                                                field.key,
                                                event.target.value
                                            )
                                        }
                                        className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm"
                                    />
                                )}
                                {field.key === "bank_account" &&
                                    form.bank_account.trim() !== "" &&
                                    !isValidIBAN(
                                        form.bank_account.replace(/\s+/g, "").toUpperCase()
                                    ) && (
                                        <p className="mt-1 text-sm text-red-600">
                                            Contul IBAN introdus nu este valid.
                                        </p>
                                    )}
                            </div>
                        ))}
                    </div>

                    <div className="mt-5 flex justify-end gap-3">
                        <button
                            type="button"
                            onClick={closeForm}
                            disabled={saving}
                            className="rounded-lg border border-gray-300 px-5 py-2 text-sm font-medium text-gray-700 disabled:opacity-50"
                        >
                            Anulează
                        </button>

                        <button
                            type="submit"
                            disabled={saving}
                            className="rounded-lg bg-dark-orange px-5 py-2 text-sm font-medium text-white disabled:opacity-50"
                        >
                            {saving ? "Se salvează..." : "Salvează"}
                        </button>
                    </div>
                </form>
            )}

            <PaginatedTable<
                    FinancialAdministrationType,
                    FinancialAdministrationsQueryParamsType
                >
                query={new GetFinancialAdministrationsQuery(axios)}
                persistQueryParamsInRouter={false}
                hasSearch={true}
                forceRefresh={forceRefresh}
                columns={[
                    {
                        label: "Denumire 1",
                        value: "name",
                    },
                    {
                        label: "Denumire 2",
                        value: "secondary_name",
                    },
                    {
                        label: "Adresă",
                        value: "address",
                    },
                    {
                        label: "Cod fiscal",
                        value: "fiscal_code",
                    },
                    {
                        label: "Telefon",
                        value: (item) => item.phone ?? "-",
                    },
                    {
                        label: "Cont bancar",
                        value: "bank_account",
                    },
                    {
                        label: "Actions",
                        value: (item) => (
                            <div className="flex gap-[1rem]">
                                <button
                                    type="button"
                                    onClick={() => openEdit(item)}
                                    title="Editează administrația financiară"
                                >
                                    <Image
                                        src="/images/edit-icon.svg"
                                        alt="Edit financial administration"
                                        width={21}
                                        height={21}
                                    />
                                </button>

                                <button
                                    type="button"
                                    disabled={deletingId !== null}
                                    onClick={() => void handleDelete(item.id)}
                                    title="Șterge administrația financiară"
                                >
                                    <Image
                                        src="/images/delete-icon.svg"
                                        alt="Delete financial administration"
                                        width={21}
                                        height={21}
                                    />
                                </button>
                            </div>
                        ),
                    },
                ]}
            />
        </section>
    );
};

export default FinancialAdministrations;
