'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface User {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  is_active: boolean;
  email_verified: boolean;
}

interface UserFormProps {
  mode: 'create' | 'edit';
  initialData?: User | null;
}

// Fields match the real `users` table exactly (see create_table.sql) —
// a single `name` column, no first/last/display name split, no avatar, no
// 2FA column. The previous version of this form was built against a
// completely different (unused, external-API-backed) schema; see
// Till_Done.md for the full story.
export default function UserForm({ mode, initialData }: UserFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';

  const [formData, setFormData] = useState({
    name: initialData?.name || '',
    email: initialData?.email || '',
    phone: initialData?.phone || '',
    is_active: initialData?.is_active ?? true,
    email_verified: initialData?.email_verified ?? false,
    password: '',
    password_confirmation: '',
  });

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleChange = (field: string, value: string | boolean) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) setErrors((prev) => ({ ...prev, [field]: '' }));
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = 'Name is required';
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }

    if (!isEditing) {
      if (!formData.password) {
        newErrors.password = 'Password is required for new users';
      } else if (formData.password.length < 8) {
        newErrors.password = 'Password must be at least 8 characters';
      } else if (formData.password !== formData.password_confirmation) {
        newErrors.password_confirmation = 'Passwords do not match';
      }
    } else if (formData.password) {
      if (formData.password.length < 8) {
        newErrors.password = 'Password must be at least 8 characters';
      } else if (formData.password !== formData.password_confirmation) {
        newErrors.password_confirmation = 'Passwords do not match';
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    if (!validate()) {
      toast.error('Please fix the validation errors');
      return;
    }

    setLoading(true);

    try {
      const url = isEditing ? `/api/users/${initialData?.id}` : '/api/users';
      const method = isEditing ? 'PUT' : 'POST';

      const submitData: Record<string, unknown> = {
        name: formData.name.trim(),
        email: formData.email.trim(),
        phone: formData.phone.trim() || null,
        is_active: formData.is_active,
        email_verified: formData.email_verified,
      };

      if (formData.password) {
        submitData.password = formData.password;
      }

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submitData),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        if (typeof data.message === 'string' && data.message.toLowerCase().includes('already exists')) {
          setErrors({ email: data.message });
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to save user'));
        }
        return;
      }

      toast.success(data.message || (isEditing ? 'User updated successfully' : 'User created successfully'));
      router.push('/admin/dashboard/users');
      router.refresh();
    } catch (err) {
      console.error('[UserForm]', err);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  }

  const formStyles = {
    background: 'var(--color-surface)',
    border: '1px solid var(--color-border)',
    borderRadius: 'var(--radius-card)',
    boxShadow: 'var(--shadow-card-md)',
    width: '100%',
    maxWidth: '700px',
  };

  const inputStyle = {
    background: 'var(--color-surface-alt)',
    border: '1px solid var(--color-border)',
    color: 'var(--color-text)',
  };

  const labelStyle = { color: 'var(--color-text-secondary)' };
  const errorStyle = { color: 'var(--color-danger)' };

  return (
    <div style={formStyles} className="p-6 md:p-8">
      <form onSubmit={handleSubmit}>
        <div className="space-y-6">
          <div className="space-y-4">
            <h3 className="text-lg font-semibold pb-2 border-b" style={{ color: 'var(--color-text)', borderColor: 'var(--color-border)' }}>
              Basic Information
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label htmlFor="name" className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Name <span className="text-red-500">*</span>
                </label>
                <input
                  id="name"
                  type="text"
                  required
                  value={formData.name}
                  onChange={(e) => handleChange('name', e.target.value)}
                  placeholder="Full name"
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.name ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.name && <p className="text-xs mt-1" style={errorStyle}>{errors.name}</p>}
              </div>

              <div>
                <label htmlFor="email" className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Email Address <span className="text-red-500">*</span>
                </label>
                <input
                  id="email"
                  type="email"
                  required
                  value={formData.email}
                  onChange={(e) => handleChange('email', e.target.value)}
                  placeholder="user@example.com"
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.email ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.email && <p className="text-xs mt-1" style={errorStyle}>{errors.email}</p>}
              </div>

              <div className="md:col-span-2">
                <label htmlFor="phone" className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Phone Number
                </label>
                <input
                  id="phone"
                  type="tel"
                  value={formData.phone}
                  onChange={(e) => handleChange('phone', e.target.value)}
                  placeholder="+92 300 1234567"
                  className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                  style={inputStyle}
                />
              </div>
            </div>
          </div>

          <div className="space-y-4">
            <h3 className="text-lg font-semibold pb-2 border-b" style={{ color: 'var(--color-text)', borderColor: 'var(--color-border)' }}>
              {isEditing ? 'Change Password (Optional)' : 'Password'}
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label htmlFor="password" className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  {isEditing ? 'New Password' : 'Password'}
                </label>
                <input
                  id="password"
                  type="password"
                  value={formData.password}
                  onChange={(e) => handleChange('password', e.target.value)}
                  placeholder={isEditing ? 'Leave blank to keep current password' : 'Enter password'}
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.password ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.password && <p className="text-xs mt-1" style={errorStyle}>{errors.password}</p>}
                <p className="text-xs mt-1" style={{ color: 'var(--color-text-muted)' }}>Minimum 8 characters</p>
              </div>

              <div>
                <label htmlFor="password_confirmation" className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Confirm Password
                </label>
                <input
                  id="password_confirmation"
                  type="password"
                  value={formData.password_confirmation}
                  onChange={(e) => handleChange('password_confirmation', e.target.value)}
                  placeholder="Confirm password"
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.password_confirmation ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.password_confirmation && <p className="text-xs mt-1" style={errorStyle}>{errors.password_confirmation}</p>}
              </div>
            </div>
          </div>

          <div className="space-y-4">
            <h3 className="text-lg font-semibold pb-2 border-b" style={{ color: 'var(--color-text)', borderColor: 'var(--color-border)' }}>
              Account Settings
            </h3>

            <div className="space-y-4">
              <div>
                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.is_active}
                    onChange={(e) => handleChange('is_active', e.target.checked)}
                    className="w-4 h-4 rounded border-gray-300 text-cta focus:ring-cta"
                  />
                  <span className="text-sm font-medium" style={labelStyle}>Active</span>
                </label>
                <p className="text-xs mt-1 ml-7" style={{ color: 'var(--color-text-muted)' }}>
                  Active users can log in to the storefront
                </p>
              </div>

              <div>
                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.email_verified}
                    onChange={(e) => handleChange('email_verified', e.target.checked)}
                    className="w-4 h-4 rounded border-gray-300 text-cta focus:ring-cta"
                  />
                  <span className="text-sm font-medium" style={labelStyle}>Email Verified</span>
                </label>
                <p className="text-xs mt-1 ml-7" style={{ color: 'var(--color-text-muted)' }}>
                  Mark email as verified
                </p>
              </div>
            </div>
          </div>

          <div className="flex gap-3 pt-4">
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  Saving...
                </span>
              ) : (isEditing ? 'Update User' : 'Create User')}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text)', border: '1px solid var(--color-border)' }}
            >
              Cancel
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
