// app/components/admin/employees/EmployeeForm.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';
import PasswordSection   from '@/app/components/admin/CommonComponents/Passwordsection';
import RoleCheckboxGroup from '@/app/components/admin/CommonComponents/Rolecheckboxgroup';
// ───────────────────────────────────────────────────────────────────────────

// ── Types ─────────────────────────────────────────────────────────────────

interface Role {
  id: string;
  name: string;
  description: string;
}

interface UserFormData {
  email:           string;
  password:        string;
  confirmPassword: string;
  first_name:      string;
  last_name:       string;
  phone:           string;
  is_active:       boolean;
  is_2fa_enabled:  boolean;
  avatar_url:      string;
  roles:           string[];
}

interface User {
  id:             string;
  email:          string;
  first_name:     string;
  last_name:      string;
  phone:          string;
  is_active:      boolean;
  is_verified:    boolean;
  is_2fa_enabled: boolean;
  avatar_url:     string;
  roles:          Role[];
  created_at:     string;
  updated_at:     string;
}

interface UserFormProps {
  userId?:      string;
  initialData?: User;
}

// ── Helpers ───────────────────────────────────────────────────────────────

const EMPTY_FORM: UserFormData = {
  email:           '',
  password:        '',
  confirmPassword: '',
  first_name:      '',
  last_name:       '',
  phone:           '',
  is_active:       true,
  is_2fa_enabled:  false,
  avatar_url:      '',
  roles:           [],
};

const toFormData = (user: User): UserFormData => ({
  email:           user.email           || '',
  password:        '',
  confirmPassword: '',
  first_name:      user.first_name      || '',
  last_name:       user.last_name       || '',
  phone:           user.phone           || '',
  is_active:       user.is_active       ?? true,
  is_2fa_enabled:  user.is_2fa_enabled  ?? false,
  avatar_url:      user.avatar_url      || '',
  roles:           user.roles?.map(r => r.id) || [],
});

// ── Component ─────────────────────────────────────────────────────────────

export default function EmployeeForm({ userId, initialData }: UserFormProps) {
  const router    = useRouter();
  const isEditing = Boolean(userId);

  const [formData, setFormData] = useState<UserFormData>(
    initialData ? toFormData(initialData) : EMPTY_FORM
  );
  const [loading,  setLoading]  = useState(false);
  const [roles,    setRoles]    = useState<Role[]>([]);

  // ── Data fetching ─────────────────────────────────────────────────────

  useEffect(() => {
    const load = async () => {
      try {
        const rolesRes = await fetch('/api/backend/admin/employees/roles');
        if (rolesRes.ok) {
          const d = await rolesRes.json();
          setRoles(d.roles || []);
        }

        if (userId && !initialData) {
          const userRes = await fetch(`/api/backend/admin/employees/${userId}`);
          if (userRes.ok) {
            const d = await userRes.json();
            setFormData(toFormData(d.user));
          }
        }
      } catch {
        toast.error('Failed to load form data');
      }
    };

    load();
  }, [userId, initialData]);

  // ── Handlers ──────────────────────────────────────────────────────────

  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 handleRoleChange = (roleId: string) => {
    setFormData(prev => ({
      ...prev,
      roles: prev.roles.includes(roleId)
        ? prev.roles.filter(id => id !== roleId)
        : [...prev.roles, roleId],
    }));
  };

  const validate = (): boolean => {
    if (!formData.email || !formData.first_name || !formData.last_name) {
      toast.error('Please fill in all required fields');
      return false;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      toast.error('Please enter a valid email address');
      return false;
    }
    if (!isEditing && !formData.password) {
      toast.error('Password is required for new users');
      return false;
    }
    if (formData.password && formData.password !== formData.confirmPassword) {
      toast.error('Passwords do not match');
      return false;
    }
    if (formData.password && formData.password.length < 6) {
      toast.error('Password must be at least 6 characters long');
      return false;
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const url    = isEditing
        ? `/api/backend/admin/employees/${userId}`
        : '/api/backend/admin/employees';
      const method = isEditing ? 'PUT' : 'POST';

      const payload: Record<string, unknown> = {
        email:          formData.email,
        first_name:     formData.first_name,
        last_name:      formData.last_name,
        phone:          formData.phone,
        is_active:      formData.is_active,
        is_2fa_enabled: formData.is_2fa_enabled,
        roles:          formData.roles,
      };
      if (formData.password)   payload.password   = formData.password;
      if (formData.avatar_url) payload.avatar_url = formData.avatar_url;

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await response.json();

      if (response.ok) {
        toast.success(isEditing ? 'Employee updated successfully' : 'Employee created successfully');
        router.push('/admin/dashboard/employees');
        router.refresh();
      } else {
        toast.error(data.error || `Failed to ${isEditing ? 'update' : 'create'} employee`);
      }
    } catch {
      toast.error(`Failed to ${isEditing ? 'update' : 'create'} employee`);
    } finally {
      setLoading(false);
    }
  };

  // ── Render ────────────────────────────────────────────────────────────

  return (
    <FormCard
      title={isEditing ? 'Edit Employee' : 'Create New Employee'}
      description={
        isEditing
          ? 'Update employee information and permissions'
          : 'Add a new employee to the system'
      }
      backHref="/admin/dashboard/employees"
      backLabel="Back to Employees"
    >
      <form onSubmit={handleSubmit} className="space-y-8">

        {/* ── Profile Image ── */}
        <FormSection title="Profile Image">
          <ImageUpload
            value={formData.avatar_url}
            onChange={url => setFormData(prev => ({ ...prev, avatar_url: url }))}
            uploadType="avatar"
            label="Upload Profile Image"
            hint="JPG, PNG, or WebP. Max 2MB. Recommended: 200×200 pixels."
            previewSize={96}
            previewShape="circle"
          />
        </FormSection>

        {/* ── Basic Information ── */}
        <FormSection title="Basic Information">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
              id="first_name"
              name="first_name"
              label="First Name"
              value={formData.first_name}
              onChange={handleInputChange}
              placeholder="Enter first name"
              required
            />

            <FormField
              id="last_name"
              name="last_name"
              label="Last Name"
              value={formData.last_name}
              onChange={handleInputChange}
              placeholder="Enter last name"
              required
            />

            <FormField
              id="email"
              name="email"
              label="Email Address"
              value={formData.email}
              onChange={handleInputChange}
              type="email"
              placeholder="Enter email address"
              required
              className="md:col-span-2"
            />

            <FormField
              id="phone"
              name="phone"
              label="Phone Number"
              value={formData.phone}
              onChange={handleInputChange}
              type="tel"
              placeholder="Enter phone number"
              className="md:col-span-2"
            />
          </div>
        </FormSection>

        {/* ── Password ── */}
        <FormSection title={isEditing ? 'Update Password' : 'Password'}>
          <PasswordSection
            password={formData.password}
            confirmPassword={formData.confirmPassword}
            onChange={handleInputChange}
            isEdit={isEditing}
          />
        </FormSection>

        {/* ── Security Settings ── */}
        <FormSection title="Security Settings">
          <FormToggle
            id="is_2fa_enabled"
            name="is_2fa_enabled"
            label="Two-Factor Authentication (2FA)"
            description="Enable two-factor authentication for enhanced security"
            checked={formData.is_2fa_enabled}
            onChange={handleInputChange}
            activeLabel="Enabled"
            inactiveLabel="Disabled"
          />
        </FormSection>

        {/* ── Roles & Permissions ── */}
        <FormSection
          title="Roles & Permissions"
          description="Assign one or more roles to control what this employee can access"
        >
          <RoleCheckboxGroup
            roles={roles}
            selectedRoleIds={formData.roles}
            onChange={handleRoleChange}
          />
        </FormSection>

        {/* ── Status ── */}
        <FormSection title="Status">
          <FormToggle
            id="is_active"
            name="is_active"
            label="Active User"
            description="Inactive users cannot log into the system"
            checked={formData.is_active}
            onChange={handleInputChange}
            activeLabel="Active"
            inactiveLabel="Inactive"
          />
        </FormSection>

        {/* ── Actions ── */}
        <FormActions
          cancelHref="/admin/dashboard/employees"
          submitLabel={isEditing ? 'Update Employee' : 'Create Employee'}
          loadingLabel={isEditing ? 'Updating...' : 'Creating...'}
          loading={loading}
        />
      </form>
    </FormCard>
  );
}