import { useEffect, useState } from "react";

import CompanyFields, {
    type CompanyDraft,
} from "@/components/profile/CompanyFields";
import type { ApiCompany, CompanyUpdatePayload } from "@/types";
import type { FieldErrors } from "@/utils/validation";

interface CompanyCardProps {
    company: ApiCompany;
    isSaving: boolean;
    onDelete: () => void;
    onLogoRemove: () => void;
    onLogoSelect: (files: File[]) => void;
    onSave: (payload: CompanyUpdatePayload) => Promise<FieldErrors>;
}

const toDraft = (company: ApiCompany): CompanyDraft => ({
    assistant_email: company.assistant_email ?? "",
    billing_email: company.billing_email ?? "",
    description: company.description ?? "",
    instagram: company.instagram ?? "",
    linkedin: company.linkedin ?? "",
    name: company.name,
    title: company.title ?? "",
    website: company.website ?? "",
    x: company.x ?? "",
});

const CompanyCard = ({
    company,
    isSaving,
    onDelete,
    onLogoRemove,
    onLogoSelect,
    onSave,
}: CompanyCardProps) => {
    const [draft, setDraft] = useState(() => toDraft(company));
    const [isConfirmingDelete, setIsConfirmingDelete] = useState(false);
    const [errors, setErrors] = useState<FieldErrors>({});

    // Only re-seed when this card is pointed at a different company, so a
    // server response (a logo upload, say) can't wipe unsaved edits.
    useEffect(() => {
        setDraft(toDraft(company));
    }, [company.id]);

    const change = (field: keyof CompanyDraft, value: string) => {
        setDraft((current) => ({ ...current, [field]: value }));
    };

    const save = async () => {
        setErrors(
            await onSave({
                assistant_email: draft.assistant_email || null,
                billing_email: draft.billing_email || null,
                description: draft.description || null,
                instagram: draft.instagram || null,
                linkedin: draft.linkedin || null,
                name: draft.name,
                title: draft.title || null,
                website: draft.website || null,
                x: draft.x || null,
            }),
        );
    };

    return (
        <section className="company-card">
            <header className="company-card__header d-flex align-items-center justify-content-between gap-3">
                <h3 className="company-card__name">
                    {draft.name || "Untitled company"}
                </h3>

                {isConfirmingDelete ? (
                    <div className="d-flex align-items-center gap-2">
                        <span className="company-card__confirm">Remove?</span>
                        <button
                            className="btn btn-outline-dark btn-sm"
                            disabled={isSaving}
                            onClick={onDelete}
                            type="button"
                        >
                            Yes, remove
                        </button>
                        <button
                            className="btn btn-outline-dark btn-sm"
                            disabled={isSaving}
                            onClick={() => setIsConfirmingDelete(false)}
                            type="button"
                        >
                            Cancel
                        </button>
                    </div>
                ) : (
                    <button
                        className="btn btn-outline-dark btn-sm"
                        disabled={isSaving}
                        onClick={() => setIsConfirmingDelete(true)}
                        type="button"
                    >
                        Remove
                    </button>
                )}
            </header>

            <CompanyFields
                draft={draft}
                errors={errors}
                isBusy={isSaving}
                logoSrc={company.logo}
                onChange={change}
                onLogoRemove={onLogoRemove}
                onLogoSelect={onLogoSelect}
            />

            <div className="form-section__actions mt-4">
                <button
                    className="btn btn-dark btn-sm"
                    disabled={isSaving}
                    onClick={() => void save()}
                    type="button"
                >
                    {isSaving ? "Saving..." : "Save"}
                </button>
            </div>
        </section>
    );
};

export default CompanyCard;
