"use client";

import { Edit3, SquarePen, Save, X } from 'lucide-react';
import React from 'react'
import { EditableTextArea } from '@/components/forms/EditableFormFields';
import { ApplicationDetailsType } from '@/schemas/admission-schema';
import { useEditableSection } from '@/hooks/useEditableSection';
import { useAppContext } from '@/contexts/AppContext';

export interface PersonalStatementInfoProps {
    application: ApplicationDetailsType;
}

type PersonalStatementInfoData = {
    personalStatement?: string;
    email?: string;
    phone_number?: string;
};

export default function PersonalStatementInfo({
    application,
}: PersonalStatementInfoProps) {
    const { state } = useAppContext();

    const buildInitialData = (): PersonalStatementInfoData => {
        const baseData: PersonalStatementInfoData = {
            personalStatement: undefined,
        };

        // Only add business school specific fields if isUBS is true
        if (state.isUBS) {
            // Use type assertion for business school specific fields
            const app = application.application as PersonalStatementInfoData;
            return {
                ...baseData,
                personalStatement: app.personalStatement || undefined,
                email: app.email || undefined,
                phone_number: app.phone_number || undefined,
            };
        }

        return baseData;
    };

    const {
        isEditing,
        formData,
        isSaving,
        hasChanges,
        handleEdit,
        handleCancel,
        handleSave,
        updateField,
    } = useEditableSection({
        applicationId: (application.application.id || '').toString(),
        initialData: buildInitialData(),
        updateType: 'application',
    });

    // Validation
    const canSave = () => {
        if (!hasChanges) return false;
        if (!formData.email || !formData.phone_number) return false;

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(formData.email)) return false;

        return true;
    };

    return (
        <div className="bg-white rounded-lg border border-gray-200 p-6">
            {/* Header with Edit/Save buttons */}
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-semibold text-gray-900 flex items-center">
                    <SquarePen className="w-10 h-10 mr-2 text-purple-600" />
                    Personal Statement
                </h3>

                <div className="flex items-center space-x-2">
                    {isEditing ? (
                        <>
                            <button
                                onClick={handleSave}
                                disabled={isSaving || !canSave()}
                                className="inline-flex items-center px-3 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                            >
                                {isSaving ? (
                                    <>
                                        <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white mr-1.5"></div>
                                        Saving...
                                    </>
                                ) : (
                                    <>
                                        <Save className="w-3 h-3 mr-1.5" />
                                        Save
                                    </>
                                )}
                            </button>
                            <button
                                onClick={handleCancel}
                                disabled={isSaving}
                                className="inline-flex items-center px-3 py-1.5 bg-gray-500 text-white text-sm font-medium rounded-lg hover:bg-gray-600 disabled:opacity-50 transition-colors"
                            >
                                <X className="w-3 h-3 mr-1.5" />
                                Cancel
                            </button>
                        </>
                    ) : (
                        <button
                            onClick={handleEdit}
                            className="inline-flex items-center px-3 py-1.5 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700 transition-colors"
                        >
                            <Edit3 className="w-3 h-3 mr-1.5" />
                            Edit
                        </button>
                    )}
                </div>
            </div>

            {/* Editable Fields */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <EditableTextArea
                    label=""
                    value={String(formData.personalStatement)}
                    onChange={(value) => updateField('personalStatement', value)}
                    placeholder=""
                    isEditing={isEditing}
                    className='col-span-2'
                    rows={5}
                />
            </div>


            {/* Unsaved changes warning */}
            {isEditing && hasChanges && (
                <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <p className="text-sm text-yellow-800">
                        You have unsaved changes. Make sure to save before leaving this section.
                    </p>
                </div>
            )}
        </div>
    );
}
