'use client';

import React, { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, User, Mail, Calendar, Shield, Edit } from 'lucide-react';
import { Role } from '@goodgo/types';
import { useUsersStore } from '../../../../stores/users-store';
import { UserCard, UserForm } from '../../../../features/shared/components/users';
import { Button } from '../../../../features/shared/components/ui/button';
import { Card } from '../../../../features/shared/components/ui/card';
import { AuthGuard } from '../../../../features/shared/middleware/auth-guard';
import { useAuthStore } from '../../../../stores/auth-store';

/**
 * EN: Admin User Detail/Edit Page
 * VI: Trang chi tiết/edit User cho Admin
 *
 * Features:
 * - Display user details
 * - Edit user information
 * - Role management
 * - Activity logs (placeholder)
 * - Breadcrumb navigation
 */
export default function AdminUserDetailPage() {
  const params = useParams();
  const router = useRouter();
  const userId = params.id as string;

  const { user: currentUser } = useAuthStore();
  const {
    currentUser: user,
    isLoadingUser,
    error,
    fetchUser,
    updateUser,
    clearCurrentUser,
    clearError,
  } = useUsersStore();

  const [isEditing, setIsEditing] = useState(false);

  // Check permissions
  const isAdmin = currentUser?.role === Role.ADMIN || currentUser?.role === Role.SUPER_ADMIN;
  const canEdit = currentUser?.role === Role.SUPER_ADMIN ||
    (currentUser?.role === Role.ADMIN && user?.role !== Role.SUPER_ADMIN);

  // Load user data
  useEffect(() => {
    if (isAdmin && userId) {
      fetchUser(userId);
    }
  }, [isAdmin, userId, fetchUser]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      clearCurrentUser();
    };
  }, [clearCurrentUser]);

  const handleEditSubmit = async (userData: any) => {
    if (!user) return;

    try {
      await updateUser(user.id, userData);
      setIsEditing(false);
      clearError();
    } catch (error) {
      // Error handled in store
    }
  };

  if (isLoadingUser) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="p-8 text-center max-w-md">
          <h2 className="text-2xl font-bold text-red-600 mb-4">Error</h2>
          <p className="text-gray-600 mb-6">{error}</p>
          <div className="flex gap-4 justify-center">
            <Button onClick={() => fetchUser(userId)}>
              Try Again
            </Button>
            <Button variant="secondary" onClick={() => router.back()}>
              Go Back
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="p-8 text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">User Not Found</h2>
          <p className="text-gray-600 mb-6">
            The user you're looking for doesn't exist.
          </p>
          <Button onClick={() => router.push('/admin/users')}>
            Back to Users
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <AuthGuard requiredRoles={[Role.ADMIN, Role.SUPER_ADMIN]}>
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-4xl mx-auto p-6">
          {/* Header */}
          <div className="flex items-center justify-between mb-8">
            <div className="flex items-center space-x-4">
              <Button
                variant="secondary"
                size="sm"
                onClick={() => router.back()}
                className="flex items-center space-x-2"
              >
                <ArrowLeft className="w-4 h-4" />
                <span>Back</span>
              </Button>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">User Details</h1>
                <p className="text-gray-600">{user.email}</p>
              </div>
            </div>

            {canEdit && !isEditing && (
              <Button
                onClick={() => setIsEditing(true)}
                className="flex items-center space-x-2"
              >
                <Edit className="w-4 h-4" />
                <span>Edit User</span>
              </Button>
            )}
          </div>

          {/* Error Display */}
          {error && (
            <Card className="p-4 mb-6 bg-red-50 border-red-200">
              <div className="flex items-center justify-between">
                <p className="text-red-800">{error}</p>
                <Button variant="secondary" size="sm" onClick={clearError}>
                  Dismiss
                </Button>
              </div>
            </Card>
          )}

          {/* Content */}
          {isEditing ? (
            <UserForm
              user={user}
              loading={isLoadingUser}
              onSubmit={handleEditSubmit}
              onCancel={() => setIsEditing(false)}
            />
          ) : (
            <div className="space-y-6">
              {/* User Card */}
              <UserCard
                user={user}
                showAdminActions={false}
                className="mb-6"
              />

              {/* User Details Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Account Information */}
                <Card className="p-6">
                  <div className="flex items-center space-x-3 mb-4">
                    <User className="w-6 h-6 text-blue-600" />
                    <h3 className="text-lg font-semibold text-gray-900">Account Information</h3>
                  </div>
                  <dl className="space-y-3">
                    <div>
                      <dt className="text-sm font-medium text-gray-500">User ID</dt>
                      <dd className="text-sm text-gray-900 font-mono">{user.id}</dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Email</dt>
                      <dd className="text-sm text-gray-900">{user.email}</dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Role</dt>
                      <dd className="text-sm text-gray-900">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${user.role === 'SUPER_ADMIN' ? 'bg-red-100 text-red-800' :
                            user.role === 'ADMIN' ? 'bg-blue-100 text-blue-800' :
                              'bg-gray-100 text-gray-800'
                          }`}>
                          {user.role}
                        </span>
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Status</dt>
                      <dd className="text-sm text-gray-900">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${user.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                          }`}>
                          {user.isActive ? 'Active' : 'Inactive'}
                        </span>
                      </dd>
                    </div>
                  </dl>
                </Card>

                {/* Account Timeline */}
                <Card className="p-6">
                  <div className="flex items-center space-x-3 mb-4">
                    <Calendar className="w-6 h-6 text-green-600" />
                    <h3 className="text-lg font-semibold text-gray-900">Account Timeline</h3>
                  </div>
                  <dl className="space-y-3">
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Created</dt>
                      <dd className="text-sm text-gray-900">
                        {new Date(user.createdAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Last Updated</dt>
                      <dd className="text-sm text-gray-900">
                        {new Date(user.updatedAt).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </dd>
                    </div>
                  </dl>
                </Card>
              </div>

              {/* Activity Logs (Placeholder) */}
              <Card className="p-6">
                <div className="flex items-center space-x-3 mb-4">
                  <Shield className="w-6 h-6 text-purple-600" />
                  <h3 className="text-lg font-semibold text-gray-900">Recent Activity</h3>
                </div>
                <div className="text-center py-8">
                  <p className="text-gray-500">
                    Activity logs will be displayed here in a future update.
                  </p>
                </div>
              </Card>
            </div>
          )}
        </div>
      </div>
    </AuthGuard>
  );
}