'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import toast from 'react-hot-toast';
import EmployeeOverrides from './EmployeeOverrides';
import EmployeePassword from './EmployeePassword';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface Role {
  id: string;
  name: string;
}

interface Permission {
  id: string;
  name: string;
  module: string;
  action: string;
  description: string | null;
}

interface Override {
  id: string;
  permission_id: string;
  override_type: 'grant' | 'deny';
  reason: string | null;
  expires_at: string | null;
  granted_at: string;
  granted_by_name?: string;
}

interface EmployeeData {
  id: string;
  employee_id: string;
  first_name: string;
  last_name: string;
  work_email: string;
  work_phone: string | null;
  date_of_birth: string | null;
  gender: string | null;
  city: string | null;
  avatar_url: string | null;
  status: string;
  role: string | null;
  overrides?: Override[];
}

interface EmployeeFormProps {
  mode: 'create' | 'edit';
  initialData?: EmployeeData | null;
  roles: Role[];
  allPermissions?: Permission[];
  canChangePassword?: boolean;
  canManageOverrides?: boolean;
}

type TabType = 'basic' | 'overrides' | 'password';

export default function EmployeeForm({ 
  mode, 
  initialData, 
  roles,
  allPermissions = [],
  canChangePassword = false,
  canManageOverrides = false,
}: EmployeeFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';
  const employeeId = initialData?.id;
  
  const [activeTab, setActiveTab] = useState<TabType>('basic');
  const [loading, setLoading] = useState(false);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);
  
  const [formData, setFormData] = useState({
    employee_id: initialData?.employee_id || '',
    first_name: initialData?.first_name || '',
    last_name: initialData?.last_name || '',
    work_email: initialData?.work_email || '',
    work_phone: initialData?.work_phone || '',
    date_of_birth: initialData?.date_of_birth?.split('T')[0] || '',
    gender: initialData?.gender || '',
    city: initialData?.city || '',
    avatar_url: initialData?.avatar_url || '',
    status: initialData?.status || 'active',
    role: initialData?.role || 'staff',
    password: '',
    confirm_password: '',
  });
  
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [passwordErrors, setPasswordErrors] = useState<Record<string, string>>({});
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  
  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };
  
  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      toast.error('Please select an image file');
      return;
    }

    if (file.size > 2 * 1024 * 1024) {
      toast.error('Image size must be less than 2MB');
      return;
    }

    setUploadingAvatar(true);
    
    try {
      const uploadFormData = new FormData();
      uploadFormData.append('file', file);
      uploadFormData.append('folder', `employees/${formData.employee_id || 'temp'}/avatar`);
      
      const uploadRes = await fetch('/api/upload', {
        method: 'POST',
        body: uploadFormData,
      });
      
      if (!uploadRes.ok) {
        throw new Error('Failed to upload avatar');
      }
      
      const uploadData = await uploadRes.json();
      
      const baseUrl = process.env.NEXT_PUBLIC_CDN_URL || 
        `https://${process.env.AWS_S3_BUCKET_NAME}.s3.${process.env.AWS_REGION}.amazonaws.com`;
      const avatarUrl = `${baseUrl}/${uploadData.data.key}`;
      
      setFormData(prev => ({ ...prev, avatar_url: avatarUrl }));
      toast.success('Profile picture uploaded successfully');
    } catch (error) {
      console.error('Avatar upload error:', error);
      toast.error('Failed to upload profile picture');
    } finally {
      setUploadingAvatar(false);
    }
  };

  const validatePassword = (password: string): string | null => {
    if (!isEditing && !password) {
      return 'Password is required for new employee';
    }
    if (password && password.length < 8) {
      return 'Password must be at least 8 characters long';
    }
    if (password && !/[A-Z]/.test(password)) {
      return 'Password must contain at least one uppercase letter';
    }
    if (password && !/[a-z]/.test(password)) {
      return 'Password must contain at least one lowercase letter';
    }
    if (password && !/[0-9]/.test(password)) {
      return 'Password must contain at least one number';
    }
    if (password && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
      return 'Password must contain at least one special character';
    }
    return null;
  };
  
  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    
    // Only validate password for create mode
    if (!isEditing) {
      const newPasswordErrors: Record<string, string> = {};
      const passwordError = validatePassword(formData.password);
      if (passwordError) {
        newPasswordErrors.password = passwordError;
      }
      if (formData.password !== formData.confirm_password) {
        newPasswordErrors.confirm_password = 'Passwords do not match';
      }
      
      if (Object.keys(newPasswordErrors).length > 0) {
        setPasswordErrors(newPasswordErrors);
        return;
      }
    }
    
    setErrors({});
    setLoading(true);
    
    try {
      const url = isEditing ? `/api/employees/${initialData?.id}` : '/api/employees';
      const method = isEditing ? 'PUT' : 'POST';
      
      const payload: Partial<typeof formData> = { ...formData };
      if (!isEditing) {
        payload.password = formData.password;
      }
      delete payload.confirm_password;
      
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      
      const data = await res.json();
      
      if (!res.ok || !data.success) {
        if (data.errors) {
          const fieldErrors: Record<string, string> = {};
          if (Array.isArray(data.errors)) {
            data.errors.forEach((err: { path: string[]; message: string }) => {
              if (err.path && err.path[0]) {
                fieldErrors[err.path[0]] = err.message;
              }
            });
          }
          setErrors(fieldErrors);
          toast.error('Please fix the validation errors');
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to save employee'));
        }
        return;
      }
      
      toast.success(data.message || (isEditing ? 'Employee updated successfully' : 'Employee created successfully'));
      
      if (!isEditing && data.data?.id) {
        router.push(`/admin/dashboard/employees/edit/${data.data.id}`);
        router.refresh();
      } else if (isEditing) {
        setRefreshTrigger(prev => prev + 1);
        router.refresh();
      }
    } catch (err) {
      console.error('[EmployeeForm]', err);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  }
  
  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)',
  };

  // Tab configuration
  const tabs: { id: TabType; label: string; icon: string; show: boolean }[] = [
    { id: 'basic', label: 'Basic Information', icon: '📝', show: true },
    { id: 'overrides', label: 'Permission Overrides', icon: '🔐', show: isEditing && canManageOverrides },
    { id: 'password', label: 'Change Password', icon: '🔑', show: isEditing && canChangePassword },
  ];

  const activeTabs = tabs.filter(tab => tab.show);

  return (
    <div className="rounded-lg overflow-hidden" style={{
      border: '1px solid var(--color-border)',
      background: 'var(--color-surface)',
    }}>
      {/* Tab Navigation */}
      <div className="flex border-b overflow-x-auto whitespace-nowrap" style={{ borderColor: 'var(--color-border)' }}>
        {activeTabs.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setActiveTab(tab.id)}
            className={`
              flex items-center gap-2 px-6 py-4 text-sm font-medium transition-all whitespace-nowrap
              ${activeTab === tab.id 
                ? 'border-b-2' 
                : 'hover:bg-surface-alt'
              }
            `}
            style={{
              borderColor: activeTab === tab.id ? 'var(--color-cta)' : 'transparent',
              color: activeTab === tab.id ? 'var(--color-cta)' : 'var(--color-text-secondary)',
              background: activeTab === tab.id ? 'var(--color-surface)' : 'transparent',
            }}
          >
            <span>{tab.icon}</span>
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div className="p-6">
        {/* Basic Information Tab */}
        {activeTab === 'basic' && (
          <form onSubmit={handleSubmit}>
            {/* Avatar Section */}
            <div className="flex items-center gap-4 mb-6 pb-6 border-b" style={{ borderColor: 'var(--color-border)' }}>
              <div className="relative w-20 h-20 rounded-full overflow-hidden bg-surface-alt border-2 shrink-0" style={{ borderColor: 'var(--color-border)' }}>
                {formData.avatar_url ? (
                  <Image
                    src={formData.avatar_url}
                    alt="Profile"
                    fill
                    className="object-cover"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-3xl" style={{ color: 'var(--color-text-secondary)' }}>
                    {formData.first_name?.[0] || formData.last_name?.[0] || '👤'}
                  </div>
                )}
              </div>
              <div>
                <input
                  type="file"
                  id="avatar-upload"
                  onChange={handleAvatarUpload}
                  accept="image/*"
                  className="hidden"
                />
                <label
                  htmlFor="avatar-upload"
                  className="inline-block px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-80 cursor-pointer"
                  style={{ background: 'var(--color-cta-light)', color: 'var(--color-cta)' }}
                >
                  {uploadingAvatar ? 'Uploading...' : 'Upload Picture'}
                </label>
                {formData.avatar_url && (
                  <button
                    type="button"
                    onClick={() => setFormData(prev => ({ ...prev, avatar_url: '' }))}
                    className="ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-80"
                    style={{ background: 'var(--color-danger-light)', color: 'var(--color-danger)' }}
                  >
                    Remove
                  </button>
                )}
              </div>
            </div>
            
            {/* Form Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Employee ID <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={formData.employee_id}
                  onChange={(e) => handleChange('employee_id', e.target.value)}
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.employee_id ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.employee_id && <p className="text-xs mt-1" style={errorStyle}>{errors.employee_id}</p>}
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Work Email <span className="text-red-500">*</span>
                </label>
                <input
                  type="email"
                  required
                  value={formData.work_email}
                  onChange={(e) => handleChange('work_email', e.target.value)}
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.work_email ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.work_email && <p className="text-xs mt-1" style={errorStyle}>{errors.work_email}</p>}
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  First Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={formData.first_name}
                  onChange={(e) => handleChange('first_name', e.target.value)}
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.first_name ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.first_name && <p className="text-xs mt-1" style={errorStyle}>{errors.first_name}</p>}
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Last Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={formData.last_name}
                  onChange={(e) => handleChange('last_name', e.target.value)}
                  className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.last_name ? 'border-red-500' : ''}`}
                  style={inputStyle}
                />
                {errors.last_name && <p className="text-xs mt-1" style={errorStyle}>{errors.last_name}</p>}
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Work Phone
                </label>
                <input
                  type="text"
                  value={formData.work_phone || ''}
                  onChange={(e) => handleChange('work_phone', e.target.value)}
                  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>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Date of Birth
                </label>
                <input
                  type="date"
                  value={formData.date_of_birth}
                  onChange={(e) => handleChange('date_of_birth', e.target.value)}
                  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>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Gender
                </label>
                <select
                  value={formData.gender}
                  onChange={(e) => handleChange('gender', e.target.value)}
                  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}
                >
                  <option value="">Select Gender</option>
                  <option value="male">Male</option>
                  <option value="female">Female</option>
                  <option value="other">Other</option>
                </select>
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  City
                </label>
                <input
                  type="text"
                  value={formData.city || ''}
                  onChange={(e) => handleChange('city', e.target.value)}
                  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>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Role
                </label>
                <select
                  value={formData.role || 'staff'}
                  onChange={(e) => handleChange('role', e.target.value)}
                  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}
                >
                  {roles.map(role => (
                    <option key={role.id} value={role.id}>{role.name}</option>
                  ))}
                </select>
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                  Status
                </label>
                <select
                  value={formData.status}
                  onChange={(e) => handleChange('status', e.target.value)}
                  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}
                >
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                  <option value="resigned">Resigned</option>
                  <option value="terminated">Terminated</option>
                </select>
              </div>
              
              {/* Password Fields - Only for Create Mode */}
              {!isEditing && (
                <div className="md:col-span-2 border-t pt-4 mt-2" style={{ borderColor: 'var(--color-border)' }}>
                  <h4 className="text-sm font-semibold mb-3" style={{ color: 'var(--color-text)' }}>
                    🔐 Account Password
                  </h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                        Password <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="password"
                        value={formData.password}
                        onChange={(e) => handleChange('password', e.target.value)}
                        className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${passwordErrors.password ? 'border-red-500' : ''}`}
                        style={inputStyle}
                        placeholder="Enter password"
                      />
                      {passwordErrors.password && <p className="text-xs mt-1" style={errorStyle}>{passwordErrors.password}</p>}
                    </div>
                    <div>
                      <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
                        Confirm Password <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="password"
                        value={formData.confirm_password}
                        onChange={(e) => handleChange('confirm_password', e.target.value)}
                        className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${passwordErrors.confirm_password ? 'border-red-500' : ''}`}
                        style={inputStyle}
                        placeholder="Confirm password"
                      />
                      {passwordErrors.confirm_password && <p className="text-xs mt-1" style={errorStyle}>{passwordErrors.confirm_password}</p>}
                    </div>
                  </div>
                </div>
              )}
            </div>
            
            {/* Form Actions */}
            <div className="flex gap-3 pt-6 mt-6 border-t" style={{ borderColor: 'var(--color-border)' }}>
              <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 Employee' : 'Create Employee')}
              </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>
          </form>
        )}

        {/* Permission Overrides Tab */}
        {activeTab === 'overrides' && employeeId && (
          <div className="py-4">
            <EmployeeOverrides 
              key={refreshTrigger}
              employeeId={employeeId}
              canManage={canManageOverrides}
              allPermissions={allPermissions}
              existingOverrides={initialData?.overrides || []}
            />
          </div>
        )}

        {/* Change Password Tab */}
        {activeTab === 'password' && employeeId && (
          <div className="py-4">
            <EmployeePassword 
              key={refreshTrigger}
              employeeId={employeeId}
              employeeEmail={initialData?.work_email || ''}
              employeeName={`${initialData?.first_name} ${initialData?.last_name}`}
            />
          </div>
        )}
      </div>
    </div>
  );
}