"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
    Award, DollarSign, Calendar, FileText, Gift,
    CheckCircle2, XCircle, Plus, X, MessageSquare
} from "lucide-react";
import { createOffer, updateOfferStatus } from "@/app/actions/offerActions";

interface OfferTabProps {
    offer: any | null;
    applicationId: string;
    isEmployer: boolean;
}

const statusConfig: Record<string, { label: string; color: string; bg: string }> = {
    pending: { label: "PENDING", color: "text-amber-800", bg: "bg-amber-100" },
    accepted: { label: "ACCEPTED", color: "text-emerald-800", bg: "bg-emerald-100" },
    declined: { label: "DECLINED", color: "text-red-800", bg: "bg-red-100" },
    negotiated: { label: "NEGOTIATING", color: "text-blue-800", bg: "bg-blue-100" },
};

export function OfferTab({ offer, applicationId, isEmployer }: OfferTabProps) {
    const router = useRouter();
    const [showForm, setShowForm] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const [formData, setFormData] = useState({
        base_salary: "",
        currency: "NGN",
        benefits: "",
        full_offer_details: "",
        response_deadline: "",
    });

    const handleCreate = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            const benefits = formData.benefits
                .split(",")
                .map((b) => b.trim())
                .filter(Boolean);

            const result = await createOffer(applicationId, {
                base_salary: formData.base_salary ? parseInt(formData.base_salary) : undefined,
                currency: formData.currency,
                benefits,
                full_offer_details: formData.full_offer_details || undefined,
                response_deadline: formData.response_deadline || undefined,
            });

            if (result.success) {
                setShowForm(false);
                router.refresh();
            }
        } catch (error) {
            console.error("Create offer failed:", error);
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleStatusUpdate = async (status: "accepted" | "declined" | "negotiated") => {
        if (!offer) return;
        try {
            await updateOfferStatus(offer.id, status);
            router.refresh();
        } catch (error) {
            console.error("Status update failed:", error);
        }
    };

    // ─── No Offer ───
    if (!offer && !showForm) {
        return (
            <div className="text-center py-16 bg-slate-50/50 border-2 border-dashed border-slate-200 rounded-2xl">
                <Award className="w-12 h-12 mx-auto mb-4 text-slate-300" />
                <h4 className="text-lg font-bold text-slate-700">
                    No Offer Extended
                </h4>
                <p className="text-sm text-slate-500 mt-1 max-w-sm mx-auto mb-6">
                    {isEmployer
                        ? "When you're ready, create an offer for this candidate."
                        : "No offer has been made yet."}
                </p>
                {isEmployer && (
                    <button
                        onClick={() => setShowForm(true)}
                        className="inline-flex items-center gap-2 px-5 py-2.5 bg-primary text-white text-sm font-semibold rounded-xl hover:bg-primary/90 transition-colors shadow-sm"
                    >
                        <Plus className="w-4 h-4" />
                        Create Offer
                    </button>
                )}
            </div>
        );
    }

    // ─── Create Offer Form ───
    if (showForm && !offer) {
        return (
            <form
                onSubmit={handleCreate}
                className="max-w-2xl bg-gradient-to-br from-primary/5 to-amber-50 border border-primary/20 rounded-2xl p-6 space-y-5"
            >
                <div className="flex items-center justify-between">
                    <h4 className="text-base font-bold text-slate-900">
                        Create Offer
                    </h4>
                    <button
                        type="button"
                        onClick={() => setShowForm(false)}
                        className="p-1 hover:bg-slate-100 rounded-lg"
                    >
                        <X className="w-5 h-5 text-slate-400" />
                    </button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {/* Salary */}
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">
                            Base Salary
                        </label>
                        <div className="flex">
                            <select
                                value={formData.currency}
                                onChange={(e) =>
                                    setFormData({ ...formData, currency: e.target.value })
                                }
                                className="px-2 py-2.5 border border-r-0 border-slate-200 rounded-l-xl text-sm bg-slate-50 focus:ring-2 focus:ring-primary/30 outline-none"
                            >
                                <option value="NGN">₦ NGN</option>
                                <option value="USD">$ USD</option>
                                <option value="EUR">€ EUR</option>
                                <option value="GBP">£ GBP</option>
                            </select>
                            <input
                                type="number"
                                value={formData.base_salary}
                                onChange={(e) =>
                                    setFormData({ ...formData, base_salary: e.target.value })
                                }
                                placeholder="e.g. 5000000"
                                className="flex-1 px-3 py-2.5 border border-slate-200 rounded-r-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none"
                            />
                        </div>
                    </div>

                    {/* Response Deadline */}
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">
                            Response Deadline
                        </label>
                        <input
                            type="date"
                            value={formData.response_deadline}
                            onChange={(e) =>
                                setFormData({ ...formData, response_deadline: e.target.value })
                            }
                            className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none"
                        />
                    </div>
                </div>

                {/* Benefits */}
                <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-1.5">
                        Benefits (comma-separated)
                    </label>
                    <input
                        type="text"
                        value={formData.benefits}
                        onChange={(e) =>
                            setFormData({ ...formData, benefits: e.target.value })
                        }
                        placeholder="Health insurance, 401k, Remote work, PTO..."
                        className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none"
                    />
                </div>

                {/* Full Details */}
                <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-1.5">
                        Full Offer Details
                    </label>
                    <textarea
                        value={formData.full_offer_details}
                        onChange={(e) =>
                            setFormData({ ...formData, full_offer_details: e.target.value })
                        }
                        rows={4}
                        placeholder="Include any additional terms, equity details, start date expectations..."
                        className="w-full px-3 py-2.5 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none resize-none"
                    />
                </div>

                <div className="flex justify-end gap-3 pt-2">
                    <button
                        type="button"
                        onClick={() => setShowForm(false)}
                        className="px-4 py-2 text-sm font-semibold text-slate-600 hover:text-slate-900"
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        disabled={isSubmitting}
                        className="px-6 py-2.5 bg-primary text-white text-sm font-semibold rounded-xl hover:bg-primary/90 transition-colors disabled:opacity-50"
                    >
                        {isSubmitting ? "Creating..." : "Send Offer"}
                    </button>
                </div>
            </form>
        );
    }

    // ─── Offer Card ───
    const status = statusConfig[offer.status] || statusConfig.pending;
    let benefits: string[] = [];
    try {
        benefits = offer.benefits ? JSON.parse(offer.benefits) : [];
    } catch {
        benefits = [];
    }

    return (
        <div className="max-w-2xl space-y-4">
            <div className="bg-gradient-to-br from-white to-slate-50 border-2 border-slate-200 rounded-2xl overflow-hidden">
                {/* Offer Header */}
                <div className="bg-gradient-to-r from-amber-500 to-orange-500 px-6 py-4 flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center">
                            <Award className="w-5 h-5 text-white" />
                        </div>
                        <div>
                            <p className="text-xs font-bold text-white/80 uppercase tracking-widest">
                                Employment Offer
                            </p>
                            <p className="text-lg font-extrabold text-white">
                                Offer Details
                            </p>
                        </div>
                    </div>
                    <span className={`px-3 py-1.5 text-xs font-bold rounded-full ${status.bg} ${status.color}`}>
                        {status.label}
                    </span>
                </div>

                {/* Offer Body */}
                <div className="p-6 space-y-5">
                    {/* Salary */}
                    {offer.base_salary && (
                        <div className="flex items-center gap-3 p-4 bg-emerald-50 border border-emerald-100 rounded-xl">
                            <DollarSign className="w-5 h-5 text-emerald-600" />
                            <div>
                                <p className="text-xs text-emerald-600 font-semibold">
                                    Base Salary
                                </p>
                                <p className="text-xl font-extrabold text-emerald-900">
                                    {offer.currency}{" "}
                                    {Number(offer.base_salary).toLocaleString()}
                                </p>
                            </div>
                        </div>
                    )}

                    {/* Response Deadline */}
                    {offer.response_deadline && (
                        <div className="flex items-center gap-3">
                            <Calendar className="w-4 h-4 text-slate-400" />
                            <div>
                                <span className="text-xs text-slate-500">
                                    Response Deadline
                                </span>
                                <p className="text-sm font-bold text-slate-900">
                                    {new Date(offer.response_deadline).toLocaleDateString(
                                        "en-US",
                                        {
                                            weekday: "long",
                                            month: "long",
                                            day: "numeric",
                                            year: "numeric",
                                        }
                                    )}
                                </p>
                            </div>
                        </div>
                    )}

                    {/* Benefits */}
                    {benefits.length > 0 && (
                        <div>
                            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                                Benefits Package
                            </p>
                            <div className="flex flex-wrap gap-2">
                                {benefits.map((b: string, i: number) => (
                                    <span
                                        key={i}
                                        className="inline-flex items-center gap-1 px-3 py-1.5 bg-blue-50 text-blue-700 text-xs font-semibold rounded-lg border border-blue-100"
                                    >
                                        <Gift className="w-3 h-3" />
                                        {b}
                                    </span>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Full details */}
                    {offer.full_offer_details && (
                        <div className="p-4 bg-slate-50 border border-slate-100 rounded-xl">
                            <div className="flex items-center gap-1.5 mb-2">
                                <FileText className="w-3.5 h-3.5 text-slate-400" />
                                <p className="text-xs font-bold text-slate-500">
                                    Additional Details
                                </p>
                            </div>
                            <p className="text-sm text-slate-700 whitespace-pre-line leading-relaxed">
                                {offer.full_offer_details}
                            </p>
                        </div>
                    )}
                </div>
            </div>

            {/* Action Buttons */}
            {offer.status === "pending" && (
                <div className="flex gap-3">
                    {isEmployer ? (
                        <>
                            <button
                                onClick={() => handleStatusUpdate("negotiated")}
                                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-semibold text-blue-700 bg-blue-50 hover:bg-blue-100 border border-blue-200 rounded-xl transition-colors"
                            >
                                <MessageSquare className="w-4 h-4" />
                                Mark Negotiating
                            </button>
                        </>
                    ) : (
                        <>
                            <button
                                onClick={() => handleStatusUpdate("accepted")}
                                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-semibold text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl transition-colors"
                            >
                                <CheckCircle2 className="w-4 h-4" />
                                Accept Offer
                            </button>
                            <button
                                onClick={() => handleStatusUpdate("declined")}
                                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-semibold text-red-700 bg-red-50 hover:bg-red-100 border border-red-200 rounded-xl transition-colors"
                            >
                                <XCircle className="w-4 h-4" />
                                Decline
                            </button>
                        </>
                    )}
                </div>
            )}
        </div>
    );
}
