"use client";

import { useState, useTransition } from "react";
import { updateCompanyProfile } from "@/app/actions/profile";
import type { Profile } from "@prisma/client";
import { Save, Loader2, X, Plus, CheckCircle } from "lucide-react";
import { FileUpload } from "@/components/ui/FileUpload";

interface CompanyProfileFormProps {
    profile: Profile | null;
}

const INDUSTRIES = ["Technology", "Finance", "Healthcare", "Education", "E-commerce", "Marketing", "Manufacturing", "Consulting", "Media", "Real Estate", "Non-profit", "Other"];
const COMPANY_SIZES = ["1-10", "11-50", "51-200", "201-500", "501-1000", "1000+"];

export function CompanyProfileForm({ profile }: CompanyProfileFormProps) {
    const [saved, setSaved] = useState(false);
    const [error, setError] = useState("");
    const [isPending, startTransition] = useTransition();
    const [hiringFor, setHiringFor] = useState<string[]>(profile?.hiring_for || []);
    const [newRole, setNewRole] = useState("");

    const addRole = () => {
        if (newRole.trim() && !hiringFor.includes(newRole.trim())) {
            setHiringFor([...hiringFor, newRole.trim()]);
            setNewRole("");
        }
    };

    const removeRole = (role: string) => setHiringFor(hiringFor.filter((r) => r !== role));

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setError("");
        setSaved(false);
        const formData = new FormData(e.currentTarget);
        formData.append("hiring_for", JSON.stringify(hiringFor));

        startTransition(async () => {
            const result = await updateCompanyProfile(formData);
            if (result?.error) setError(result.error);
            else setSaved(true);
        });
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6">
            {/* Basic Info */}
            <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-5">
                <h2 className="font-bold text-slate-900 text-lg">Company Information</h2>

                <div className="mb-6 pb-6 border-b border-slate-100">
                    <h3 className="text-sm font-semibold text-slate-700 mb-3">Company Logo</h3>
                    <input type="hidden" name="company_logo_url" id="company_logo_hidden" defaultValue={profile?.company_logo_url || ""} />
                    <FileUpload 
                        label="Upload Logo (JPEG, PNG, WEBP)"
                        accept="image/jpeg, image/png, image/webp"
                        maxSizeMB={2}
                        defaultUrl={profile?.company_logo_url || undefined}
                        onUploadSuccess={(url) => {
                            const hiddenInput = document.getElementById("company_logo_hidden") as HTMLInputElement;
                            if (hiddenInput) hiddenInput.value = url;
                        }}
                    />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Company Name *</label>
                        <input name="company_name" defaultValue={profile?.company_name || ""} required
                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm"
                            placeholder="e.g. Acme Corp" />
                    </div>
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Website</label>
                        <input name="company_website" type="url" defaultValue={profile?.company_website || ""}
                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm"
                            placeholder="https://yourcompany.com" />
                    </div>
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">HQ Location</label>
                        <input name="company_location" defaultValue={profile?.company_location || ""}
                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm"
                            placeholder="e.g. Lagos, Nigeria" />
                    </div>
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Industry</label>
                        <select name="company_industry" defaultValue={profile?.company_industry || ""}
                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm bg-white">
                            <option value="">Select industry...</option>
                            {INDUSTRIES.map((ind) => <option key={ind} value={ind}>{ind}</option>)}
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-1.5">Company Size</label>
                        <select name="company_size" defaultValue={profile?.company_size || ""}
                            className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm bg-white">
                            <option value="">Select size...</option>
                            {COMPANY_SIZES.map((s) => <option key={s} value={s}>{s} employees</option>)}
                        </select>
                    </div>
                </div>

                <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-1.5">About the Company</label>
                    <textarea name="company_description" defaultValue={profile?.company_description || ""} rows={5}
                        className="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm resize-none"
                        placeholder="Describe what your company does, your culture, and why people should work here..." />
                </div>
            </div>

            {/* Hiring For */}
            <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-4">
                <h2 className="font-bold text-slate-900 text-lg">Currently Hiring For</h2>
                <p className="text-sm text-slate-500">Add roles you&apos;re actively recruiting for.</p>

                <div className="flex flex-wrap gap-2">
                    {hiringFor.map((role) => (
                        <span key={role} className="flex items-center gap-1.5 px-3 py-1.5 bg-indigo-50 text-indigo-700 border border-indigo-200 rounded-full text-sm font-medium">
                            {role}
                            <button type="button" onClick={() => removeRole(role)} className="text-indigo-400 hover:text-indigo-700 transition-colors">
                                <X className="w-3.5 h-3.5" />
                            </button>
                        </span>
                    ))}
                </div>

                <div className="flex gap-2">
                    <input value={newRole} onChange={(e) => setNewRole(e.target.value)}
                        onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addRole())}
                        className="flex-1 px-4 py-2.5 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-sm"
                        placeholder="e.g. Senior React Developer" />
                    <button type="button" onClick={addRole}
                        className="flex items-center gap-1.5 px-4 py-2.5 rounded-xl border border-slate-200 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-colors">
                        <Plus className="w-4 h-4" /> Add
                    </button>
                </div>
            </div>

            {/* Status & Submit */}
            {error && <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-xl px-4 py-3">{error}</p>}
            {saved && (
                <div className="flex items-center gap-2 text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-xl px-4 py-3">
                    <CheckCircle className="w-4 h-4" /> Company profile saved successfully!
                </div>
            )}

            <button type="submit" disabled={isPending}
                className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl font-semibold hover:bg-blue-700 transition-colors shadow-lg shadow-primary/25 disabled:opacity-50">
                {isPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : <><Save className="w-4 h-4" /> Save Company Profile</>}
            </button>
        </form>
    );
}
