"use client";

import { useState } from "react";
import { Plus, Edit2, Trash2, Briefcase, X, Check } from "lucide-react";
import type { Experience } from "@/lib/db";
import { addWorkExperience, updateWorkExperience, deleteWorkExperience } from "@/app/actions/profileActions";
import { useRouter } from "next/navigation";

interface WorkExperienceManagerProps {
    userId: string;
    experiences: Experience[];
}

export function WorkExperienceManager({ userId, experiences: initialExperiences }: WorkExperienceManagerProps) {
    const router = useRouter();
    const [experiences, setExperiences] = useState<Experience[]>(initialExperiences);
    const [isAdding, setIsAdding] = useState(false);
    const [editingId, setEditingId] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);

    // Form state
    const [formData, setFormData] = useState<Partial<Experience>>({
        title: "",
        company: "",
        location: "",
        startDate: "",
        endDate: "",
        current: false,
        description: "",
    });

    const resetForm = () => {
        setFormData({
            title: "",
            company: "",
            location: "",
            startDate: "",
            endDate: "",
            current: false,
            description: "",
        });
        setIsAdding(false);
        setEditingId(null);
    };

    const handleAdd = async () => {
        if (!formData.title || !formData.company || !formData.startDate) {
            alert("Please fill in required fields (Position, Company, Start Date)");
            return;
        }

        setLoading(true);
        const result = await addWorkExperience(userId, formData as Omit<Experience, 'id'>);

        if (result.success && result.experience) {
            setExperiences([...experiences, result.experience]);
            resetForm();
            router.refresh();
        } else {
            alert(result.error || "Failed to add experience");
        }
        setLoading(false);
    };

    const handleEdit = (exp: Experience) => {
        setFormData(exp);
        setEditingId(exp.id);
        setIsAdding(false);
    };

    const handleUpdate = async () => {
        if (!editingId || !formData.title || !formData.company || !formData.startDate) {
            alert("Please fill in required fields");
            return;
        }

        setLoading(true);
        const result = await updateWorkExperience(userId, editingId, formData);

        if (result.success) {
            setExperiences(experiences.map(exp =>
                exp.id === editingId ? { ...exp, ...formData } as Experience : exp
            ));
            resetForm();
            router.refresh();
        } else {
            alert(result.error || "Failed to update experience");
        }
        setLoading(false);
    };

    const handleDelete = async (id: string) => {
        if (!confirm("Are you sure you want to delete this work experience?")) {
            return;
        }

        setLoading(true);
        const result = await deleteWorkExperience(userId, id);

        if (result.success) {
            setExperiences(experiences.filter(exp => exp.id !== id));
            router.refresh();
        } else {
            alert(result.error || "Failed to delete experience");
        }
        setLoading(false);
    };

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-slate-900 flex items-center gap-2">
                    <Briefcase className="h-5 w-5 text-primary" />
                    Work Experience
                </h3>
                {!isAdding && !editingId && (
                    <button
                        onClick={() => setIsAdding(true)}
                        className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white hover:bg-blue-700 transition-colors text-sm font-medium"
                    >
                        <Plus className="h-4 w-4" />
                        Add Experience
                    </button>
                )}
            </div>

            {/* Add/Edit Form */}
            {(isAdding || editingId) && (
                <div className="bg-slate-50 rounded-xl p-4 border border-slate-200 space-y-4">
                    <div className="flex items-center justify-between mb-2">
                        <h4 className="font-semibold text-slate-900">
                            {editingId ? "Edit Experience" : "Add New Experience"}
                        </h4>
                        <button
                            onClick={resetForm}
                            className="text-slate-400 hover:text-slate-600 transition-colors"
                        >
                            <X className="h-5 w-5" />
                        </button>
                    </div>

                    <div className="grid gap-4 md:grid-cols-2">
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-2">
                                Position Title <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={formData.title}
                                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                                placeholder="e.g. Senior Frontend Developer"
                                className="w-full rounded-lg border border-slate-200 px-4 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-2">
                                Company <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={formData.company}
                                onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                                placeholder="e.g. TechCorp Solutions"
                                className="w-full rounded-lg border border-slate-200 px-4 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none"
                            />
                        </div>
                        <div className="md:col-span-2">
                            <label className="block text-sm font-semibold text-slate-700 mb-2">Location</label>
                            <input
                                type="text"
                                value={formData.location}
                                onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                                placeholder="e.g. San Francisco, CA"
                                className="w-full rounded-lg border border-slate-200 px-4 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-2">
                                Start Date <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="date"
                                value={formData.startDate}
                                onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
                                className="w-full rounded-lg border border-slate-200 px-4 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-2">End Date</label>
                            <input
                                type="date"
                                value={formData.endDate}
                                onChange={(e) => setFormData({ ...formData, endDate: e.target.value })}
                                disabled={formData.current}
                                className="w-full rounded-lg border border-slate-200 px-4 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none disabled:bg-slate-100"
                            />
                        </div>
                        <div className="md:col-span-2">
                            <label className="flex items-center gap-2 text-sm font-medium text-slate-700 cursor-pointer">
                                <input
                                    type="checkbox"
                                    checked={formData.current}
                                    onChange={(e) => setFormData({ ...formData, current: e.target.checked, endDate: e.target.checked ? "" : formData.endDate })}
                                    className="rounded border-slate-300 text-primary focus:ring-primary/20"
                                />
                                I currently work here
                            </label>
                        </div>
                        <div className="md:col-span-2">
                            <label className="block text-sm font-semibold text-slate-700 mb-2">Description</label>
                            <textarea
                                value={formData.description}
                                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                rows={4}
                                placeholder="Describe your responsibilities and achievements..."
                                className="w-full rounded-lg border border-slate-200 px-4 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none resize-none"
                            />
                        </div>
                    </div>

                    <div className="flex gap-2 justify-end">
                        <button
                            onClick={resetForm}
                            className="px-4 py-2 rounded-lg border border-slate-200 text-slate-700 hover:bg-slate-50 transition-colors text-sm font-medium"
                        >
                            Cancel
                        </button>
                        <button
                            onClick={editingId ? handleUpdate : handleAdd}
                            disabled={loading}
                            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white hover:bg-blue-700 transition-colors text-sm font-medium disabled:opacity-50"
                        >
                            <Check className="h-4 w-4" />
                            {loading ? "Saving..." : editingId ? "Update" : "Add"}
                        </button>
                    </div>
                </div>
            )}

            {/* Experience List */}
            <div className="space-y-3">
                {experiences.length === 0 ? (
                    <p className="text-slate-500 text-sm text-center py-8">No work experience added yet</p>
                ) : (
                    experiences.map((exp) => (
                        <div
                            key={exp.id}
                            className="bg-white rounded-xl border border-slate-200 p-4 hover:border-primary/30 transition-colors"
                        >
                            <div className="flex items-start justify-between">
                                <div className="flex-1">
                                    <h4 className="font-bold text-slate-900">{exp.title}</h4>
                                    <p className="text-primary font-medium">{exp.company}</p>
                                    {exp.location && (
                                        <p className="text-sm text-slate-500">{exp.location}</p>
                                    )}
                                    <p className="text-sm text-slate-400 mt-1">
                                        {new Date(exp.startDate).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })} - {' '}
                                        {exp.current ? 'Present' : new Date(exp.endDate!).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
                                    </p>
                                    {exp.description && (
                                        <p className="text-slate-600 mt-2 text-sm">{exp.description}</p>
                                    )}
                                </div>
                                <div className="flex gap-2 ml-4">
                                    <button
                                        onClick={() => handleEdit(exp)}
                                        className="p-2 text-slate-400 hover:text-primary hover:bg-primary/5 rounded-lg transition-colors"
                                    >
                                        <Edit2 className="h-4 w-4" />
                                    </button>
                                    <button
                                        onClick={() => handleDelete(exp.id)}
                                        className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                    >
                                        <Trash2 className="h-4 w-4" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))
                )}
            </div>
        </div>
    );
}
