// app/components/admin/users/UserForm.tsx
'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';

// ── Shared form components ──────────────────────────────────────────────────
import FormCard from '@/app/components/admin/CommonComponents/Formcard';
import FormSection from '@/app/components/admin/CommonComponents/Formsection';
import FormField from '@/app/components/admin/CommonComponents/Formfield';
import FormToggle from '@/app/components/admin/CommonComponents/Formtoggle';
import FormActions from '@/app/components/admin/CommonComponents/Formactions';
import ImageUpload from '@/app/components/admin/CommonComponents/Imageupload';
// ───────────────────────────────────────────────────────────────────────────

// ── Types ──────────────────────────────────────────────────────────────────

interface UserFormData {
  email: string;
  first_name: string;
  last_name: string;
  display_name: string;
  phone: string;
  avatar_url: string;
  is_active: boolean;
  email_verified: boolean;
  two_factor_enabled: boolean;
  password?: string;
  password_confirmation?: string;
}

interface User extends UserFormData {
  id: string;
  created_at: string;
  updated_at: string;
  last_login_at: string | null;
  failed_login_attempts: number;
}

interface UserFormProps {
  userId?: string;
  initialData?: User;
}

// ── Helpers ────────────────────────────────────────────────────────────────

const EMPTY_FORM: UserFormData = {
  email: '',
  first_name: '',
  last_name: '',
  display_name: '',
  phone: '',
  avatar_url: '',
  is_active: true,
  email_verified: false,
  two_factor_enabled: false,
  password: '',
  password_confirmation: '',
};

const toFormData = (src: User): UserFormData => ({
  email: src.email || '',
  first_name: src.first_name || '',
  last_name: src.last_name || '',
  display_name: src.display_name || '',
  phone: src.phone || '',
  avatar_url: src.avatar_url || '',
  is_active: src.is_active ?? true,
  email_verified: src.email_verified ?? false,
  two_factor_enabled: src.two_factor_enabled ?? false,
});

// ── Component ──────────────────────────────────────────────────────────────

export default function UserForm({ userId, initialData }: UserFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<UserFormData>(
    initialData ? toFormData(initialData) : EMPTY_FORM
  );

  useEffect(() => {
    const load = async () => {
      try {
        if (userId && !initialData) {
          const userRes = await fetch(`/api/backend/admin/users/${userId}`);
          if (userRes.ok) {
            const data = await userRes.json();
            setFormData(toFormData(data.user));
          }
        }
      } catch {
        toast.error('Failed to load form data');
      }
    };
    load();
  }, [userId, initialData]);

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    const checked = type === 'checkbox' ? (e.target as HTMLInputElement).checked : undefined;
    setFormData((prev) => ({ ...prev, [name]: checked !== undefined ? checked : value }));
  };

  const validate = (): boolean => {
    if (!formData.email.trim()) { toast.error('Email is required'); return false; }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) { toast.error('Please enter a valid email address'); return false; }

    if (!userId) {
      if (!formData.password) { toast.error('Password is required for new users'); return false; }
      if (formData.password.length < 8) { toast.error('Password must be at least 8 characters'); return false; }
      if (formData.password !== formData.password_confirmation) { toast.error('Passwords do not match'); return false; }
    } else {
      if (formData.password) {
        if (formData.password.length < 8) { toast.error('Password must be at least 8 characters'); return false; }
        if (formData.password !== formData.password_confirmation) { toast.error('Passwords do not match'); return false; }
      }
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const url = userId ? `/api/backend/admin/users/${userId}` : '/api/backend/admin/users';
      const submitData = { ...formData };
      if (!submitData.password) {
        delete submitData.password;
        delete submitData.password_confirmation;
      } else {
        delete submitData.password_confirmation;
      }

      const response = await fetch(url, {
        method: userId ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submitData),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(userId ? 'User updated successfully' : 'User created successfully');
        router.push('/admin/dashboard/users');
        router.refresh();
      } else {
        toast.error(data.error || `Failed to ${userId ? 'update' : 'create'} user`);
      }
    } catch {
      toast.error(`Failed to ${userId ? 'update' : 'create'} user`);
    } finally {
      setLoading(false);
    }
  };

  const isEditing = Boolean(userId);

  return (
    <FormCard
      title={isEditing ? 'Edit User' : 'Create New User'}
      description={isEditing ? 'Update user information and settings' : 'Add a new user to the system'}
      backHref="/admin/dashboard/users"
      backLabel="Back to Users"
    >
      <form onSubmit={handleSubmit} className="space-y-8">

        <FormSection title="Basic Information">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
              id="email" name="email" label="Email Address" type="email"
              value={formData.email} onChange={handleInputChange}
              placeholder="user@example.com" required disabled={isEditing}
              hint={isEditing ? "Email cannot be changed after creation" : ""}
            />
            <FormField id="first_name" name="first_name" label="First Name"
              value={formData.first_name} onChange={handleInputChange} placeholder="Enter first name" />
            <FormField id="last_name" name="last_name" label="Last Name"
              value={formData.last_name} onChange={handleInputChange} placeholder="Enter last name" />
            <FormField id="display_name" name="display_name" label="Display Name"
              value={formData.display_name} onChange={handleInputChange}
              placeholder="How the user will be displayed" hint="If empty, first and last name will be used" />
            <FormField id="phone" name="phone" label="Phone Number" type="tel"
              value={formData.phone} onChange={handleInputChange} placeholder="+1 234 567 8900" />
          </div>
        </FormSection>

        <FormSection title="Profile Picture">
          <ImageUpload
            value={formData.avatar_url}
            onChange={(url) => setFormData((prev) => ({ ...prev, avatar_url: url }))}
            uploadType="avatar"
            label="Upload Profile Picture"
          />
        </FormSection>

        <FormSection title={isEditing ? "Change Password (Optional)" : "Password"}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
              id="password" name="password" label={isEditing ? "New Password" : "Password"} type="password"
              value={formData.password || ''} onChange={handleInputChange}
              placeholder={isEditing ? "Leave blank to keep current password" : "Enter password"}
              hint={isEditing ? "Minimum 8 characters. Leave blank to keep current password." : "Minimum 8 characters"}
            />
            <FormField
              id="password_confirmation" name="password_confirmation" label="Confirm Password" type="password"
              value={formData.password_confirmation || ''} onChange={handleInputChange} placeholder="Confirm password"
            />
          </div>
        </FormSection>

        <FormSection title="Account Settings">
          <div className="space-y-4">
            <FormToggle id="is_active" name="is_active" label="Account Status"
              description="Active users can log in to the system" checked={formData.is_active}
              onChange={handleInputChange} activeLabel="Active" inactiveLabel="Inactive" />
            <FormToggle id="email_verified" name="email_verified" label="Email Verification"
              description="Mark email as verified" checked={formData.email_verified}
              onChange={handleInputChange} activeLabel="Verified" inactiveLabel="Not Verified" />
            <FormToggle id="two_factor_enabled" name="two_factor_enabled" label="Two-Factor Authentication"
              description="Enable 2FA for this user (using email)" checked={formData.two_factor_enabled}
              onChange={handleInputChange} activeLabel="Enabled" inactiveLabel="Disabled" />
          </div>
        </FormSection>

        <FormActions
          cancelHref="/admin/dashboard/users"
          submitLabel={isEditing ? 'Update User' : 'Create User'}
          loadingLabel={isEditing ? 'Updating...' : 'Creating...'}
          loading={loading}
        />
      </form>
    </FormCard>
  );
}