'use client';

import { useState, useEffect, FormEvent, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

interface Customer {
    id: string;
    name: string;
    url: string;
    email: string;
    createdAt: string;
    modifiedAt: string;
}

interface EditCustomerProps {
    id?: string; // Optional for new customer
}

export default function EditCustomer({ id }: EditCustomerProps) {
    const router = useRouter();
    const [formData, setFormData] = useState({
        name: '',
        url: '',
        email: '',
    });
    const [isLoading, setIsLoading] = useState(!!id); // Only loading if editing
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Fetch customer data if editing
    useEffect(() => {
        const fetchCustomer = async () => {
            if (!id) {
                setIsLoading(false);
                return;
            }

            try {
                const response = await fetch(`/api/customers/${id}`);

                if (!response.ok) {
                    throw new Error('Failed to fetch customer');
                }

                const customer: Customer = await response.json();

                setFormData({
                    name: customer.name,
                    url: customer.url || '',
                    email: customer.email,
                });

                setIsLoading(false);
            } catch (err) {
                setError('Failed to load customer data');
                setIsLoading(false);
            }
        };

        fetchCustomer();
    }, [id]);

    const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        setError(null);

        try {
            // Validate form
            if (!formData.name || !formData.email) {
                throw new Error('Name and email are required');
            }

            // Determine if creating or updating
            const url = id ? `/api/customers/${id}` : '/api/customers';
            const method = id ? 'PUT' : 'POST';

            // Submit the form
            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.error || `Failed to ${id ? 'update' : 'create'} customer`);
            }

            // Redirect to customers list on success
            router.push('/admin/customers');
            router.refresh();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'An error occurred');
            setIsSubmitting(false);
        }
    };

    if (isLoading) {
        return <div className="text-center py-10">Loading...</div>;
    }

    return (
        <div>
            <div className="flex justify-between items-center mb-6">
                <h1 className="text-2xl font-semibold text-gray-900">
                    {id ? 'Edit Customer' : 'Add New Customer'}
                </h1>
                <Link
                    href="/admin/customers"
                    className="text-indigo-600 hover:text-indigo-900"
                >
                    Back to Customers
                </Link>
            </div>

            {error && (
                <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
                    <div className="flex">
                        <div className="flex-shrink-0">
                            <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                            </svg>
                        </div>
                        <div className="ml-3">
                            <p className="text-sm text-red-700">{error}</p>
                        </div>
                    </div>
                </div>
            )}

            <form onSubmit={handleSubmit} className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="name">
                        Name
                    </label>
                    <input
                        className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                        id="name"
                        type="text"
                        name="name"
                        value={formData.name}
                        onChange={handleChange}
                        placeholder="Customer Name"
                        required
                    />
                </div>

                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="url">
                        URL
                    </label>
                    <input
                        className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                        id="url"
                        type="text"
                        name="url"
                        value={formData.url}
                        onChange={handleChange}
                        placeholder="Website URL (optional)"
                    />
                </div>

                <div className="mb-6">
                    <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email">
                        Email
                    </label>
                    <input
                        className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                        id="email"
                        type="email"
                        name="email"
                        value={formData.email}
                        onChange={handleChange}
                        placeholder="Email Address"
                        required
                    />
                </div>

                <div className="flex items-center justify-between">
                    <button
                        className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline disabled:opacity-50"
                        type="submit"
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? (id ? 'Updating...' : 'Creating...') : (id ? 'Update Customer' : 'Create Customer')}
                    </button>
                    <Link
                        href="/admin/customers"
                        className="inline-block align-baseline font-bold text-sm text-indigo-600 hover:text-indigo-800"
                    >
                        Cancel
                    </Link>
                </div>
            </form>
        </div>
    );
}
