'use client';

import { useState, useEffect, Suspense } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import { 
  ArrowLeft,
  Pencil,
  Phone,
  Mail,
  Calendar,
  MapPin,
  User,
  UserCheck,
  Building,
  GraduationCap,
  FileText,
  Award,
  Trash2
} from 'lucide-react';
import ProtectedRoute from '../../protected-route';
import SidebarLayout from '../../components/sidebar-layout';
import { useTranslations } from '../../hooks/useTranslations';

interface StaffMember {
  _id: string;
  name: string;
  email: string;
  role: string;
  phone?: string;
  address?: string;
  dateOfBirth?: string;
  gender?: string;
  specialization?: string;
  department?: string;
  licenseNumber?: string;
  qualifications?: string[];
  yearsOfExperience?: number;
  bio?: string;
  createdAt?: string;
  updatedAt?: string;
}

function StaffDetailsContent() {
  const params = useParams();
  const router = useRouter();
  const { data: session } = useSession();
  const { t } = useTranslations();
  const [staff, setStaff] = useState<StaffMember | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const isAdmin = session?.user?.role === 'admin';

  useEffect(() => {
    if (!isAdmin) {
      router.push('/');
      return;
    }
    fetchStaffDetails();
  }, [isAdmin, router, params.id]);

  const fetchStaffDetails = async () => {
    try {
      const response = await fetch(`/api/staff?id=${params.id}`);
      if (response.ok) {
        const data = await response.json();
        setStaff(data);
      } else {
        setError(t('staff.detailsPage.notFound'));
      }
    } catch (error) {
      console.error('Error fetching staff details:', error);
      setError(t('staff.detailsPage.errorDescription'));
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!staff) return;
    
    if (!confirm(t('staff.detailsPage.confirmDelete', { name: staff.name }))) {
      return;
    }

    try {
      const response = await fetch(`/api/staff?id=${staff._id}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        alert(t('staff.detailsPage.deleteSuccess'));
        router.push('/staff');
      } else {
        const errorData = await response.json();
        alert(`${t('staff.detailsPage.deleteFailed')}: ${errorData.error || 'Unknown error'}`);
      }
    } catch (error) {
      console.error('Error deleting staff:', error);
      alert(t('staff.detailsPage.deleteError'));
    }
  };

  if (loading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('common.loading')} description={t('staff.detailsPage.pleaseWait')}>
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
              <p className="mt-4 text-gray-600">{t('staff.detailsPage.loadingDetails')}</p>
            </div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  if (error || !staff) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('staff.detailsPage.errorTitle')} description={t('staff.detailsPage.errorDescription')}>
          <div className="max-w-4xl mx-auto">
            <div className="mb-6">
              <Link
                href="/staff"
                className="inline-flex items-center space-x-2 text-gray-600 hover:text-gray-900 transition-colors"
              >
                <ArrowLeft className="h-4 w-4" />
                <span>{t('staff.detailsPage.backToStaff')}</span>
              </Link>
            </div>
            <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
              <p className="text-red-800">{error || t('staff.detailsPage.notFound')}</p>
            </div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <SidebarLayout 
        title={t('staff.detailsPage.title')}
        description={t('staff.detailsPage.description')}
      >
        <div className="max-w-4xl mx-auto">
          {/* Back Button */}
          <div className="mb-6">
            <Link
              href="/staff"
              className="inline-flex items-center space-x-2 text-gray-600 hover:text-gray-900 transition-colors"
            >
              <ArrowLeft className="h-4 w-4" />
              <span>{t('staff.detailsPage.backToStaff')}</span>
            </Link>
          </div>

          {/* Staff Profile Card */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            {/* Header */}
            <div className="bg-gradient-to-r from-green-600 to-emerald-600 px-6 py-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center">
                    <UserCheck className="h-8 w-8 text-white" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-white">{staff.name}</h2>
                    <p className="text-white/80 capitalize">{staff.role}</p>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <Link
                    href={`/staff/${staff._id}/edit`}
                    className="inline-flex items-center space-x-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-lg transition-colors"
                  >
                    <Pencil className="h-4 w-4" />
                    <span>{t('common.edit')}</span>
                  </Link>
                  {staff.email !== session?.user?.email && (
                    <button
                      onClick={handleDelete}
                      className="inline-flex items-center space-x-2 px-4 py-2 bg-red-500/80 hover:bg-red-500 text-white rounded-lg transition-colors"
                    >
                      <Trash2 className="h-4 w-4" />
                      <span>{t('common.delete')}</span>
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* Content */}
            <div className="p-6 space-y-6">
              {/* Contact Information */}
              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                  <User className="h-5 w-5 mr-2 text-gray-500" />
                  {t('staff.detailsPage.contactInfo')}
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                    <Mail className="h-5 w-5 text-gray-400" />
                    <div>
                      <p className="text-xs text-gray-500">{t('staff.detailsPage.email')}</p>
                      <p className="text-sm font-medium text-gray-900">{staff.email}</p>
                    </div>
                  </div>
                  {staff.phone && (
                    <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                      <Phone className="h-5 w-5 text-gray-400" />
                      <div>
                        <p className="text-xs text-gray-500">{t('staff.detailsPage.phone')}</p>
                        <p className="text-sm font-medium text-gray-900">{staff.phone}</p>
                      </div>
                    </div>
                  )}
                  {staff.address && (
                    <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg md:col-span-2">
                      <MapPin className="h-5 w-5 text-gray-400" />
                      <div>
                        <p className="text-xs text-gray-500">{t('staff.detailsPage.address')}</p>
                        <p className="text-sm font-medium text-gray-900">{staff.address}</p>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Personal Information */}
              {(staff.dateOfBirth || staff.gender) && (
                <div className="border-t border-gray-200 pt-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <Calendar className="h-5 w-5 mr-2 text-gray-500" />
                    {t('staff.detailsPage.personalInfo')}
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {staff.dateOfBirth && (
                      <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <Calendar className="h-5 w-5 text-gray-400" />
                        <div>
                          <p className="text-xs text-gray-500">{t('staff.detailsPage.dateOfBirth')}</p>
                          <p className="text-sm font-medium text-gray-900">
                            {new Date(staff.dateOfBirth).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                    )}
                    {staff.gender && (
                      <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <User className="h-5 w-5 text-gray-400" />
                        <div>
                          <p className="text-xs text-gray-500">{t('staff.detailsPage.gender')}</p>
                          <p className="text-sm font-medium text-gray-900 capitalize">{staff.gender}</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Professional Information */}
              {(staff.specialization || staff.department || staff.licenseNumber || staff.yearsOfExperience) && (
                <div className="border-t border-gray-200 pt-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <Building className="h-5 w-5 mr-2 text-gray-500" />
                    {t('staff.detailsPage.professionalInfo')}
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {staff.specialization && (
                      <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <GraduationCap className="h-5 w-5 text-gray-400" />
                        <div>
                          <p className="text-xs text-gray-500">{t('staff.detailsPage.specialization')}</p>
                          <p className="text-sm font-medium text-gray-900">{staff.specialization}</p>
                        </div>
                      </div>
                    )}
                    {staff.department && (
                      <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <Building className="h-5 w-5 text-gray-400" />
                        <div>
                          <p className="text-xs text-gray-500">{t('staff.detailsPage.department')}</p>
                          <p className="text-sm font-medium text-gray-900">{staff.department}</p>
                        </div>
                      </div>
                    )}
                    {staff.licenseNumber && (
                      <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <FileText className="h-5 w-5 text-gray-400" />
                        <div>
                          <p className="text-xs text-gray-500">{t('staff.detailsPage.licenseNumber')}</p>
                          <p className="text-sm font-medium text-gray-900">{staff.licenseNumber}</p>
                        </div>
                      </div>
                    )}
                    {staff.yearsOfExperience !== undefined && (
                      <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <Award className="h-5 w-5 text-gray-400" />
                        <div>
                          <p className="text-xs text-gray-500">{t('staff.detailsPage.yearsOfExperience')}</p>
                          <p className="text-sm font-medium text-gray-900">{staff.yearsOfExperience} {t('staff.detailsPage.years')}</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Qualifications */}
              {staff.qualifications && staff.qualifications.length > 0 && (
                <div className="border-t border-gray-200 pt-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                    <Award className="h-5 w-5 mr-2 text-gray-500" />
                    {t('staff.detailsPage.qualifications')}
                  </h3>
                  <div className="flex flex-wrap gap-2">
                    {staff.qualifications.map((qual, index) => (
                      <span
                        key={index}
                        className="inline-flex items-center px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm"
                      >
                        {qual}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Biography */}
              {staff.bio && (
                <div className="border-t border-gray-200 pt-6">
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('staff.detailsPage.biography')}</h3>
                  <p className="text-gray-700 whitespace-pre-wrap">{staff.bio}</p>
                </div>
              )}

              {/* Account Information */}
              <div className="border-t border-gray-200 pt-6">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('staff.detailsPage.accountInfo')}</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {staff.createdAt && (
                    <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                      <Calendar className="h-5 w-5 text-gray-400" />
                      <div>
                        <p className="text-xs text-gray-500">{t('staff.detailsPage.createdAt')}</p>
                        <p className="text-sm font-medium text-gray-900">
                          {new Date(staff.createdAt).toLocaleString()}
                        </p>
                      </div>
                    </div>
                  )}
                  {staff.updatedAt && (
                    <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                      <Calendar className="h-5 w-5 text-gray-400" />
                      <div>
                        <p className="text-xs text-gray-500">{t('staff.detailsPage.lastUpdated')}</p>
                        <p className="text-sm font-medium text-gray-900">
                          {new Date(staff.updatedAt).toLocaleString()}
                        </p>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}

function StaffDetailsFallback() {
  const { t } = useTranslations();
  return (
    <SidebarLayout title={t('common.loading')} description={t('staff.detailsPage.pleaseWait')}>
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">{t('staff.detailsPage.loadingDetails')}</p>
        </div>
      </div>
    </SidebarLayout>
  );
}

export default function StaffDetailsPage() {
  return (
    <ProtectedRoute>
      <Suspense fallback={<StaffDetailsFallback />}>
        <StaffDetailsContent />
      </Suspense>
    </ProtectedRoute>
  );
}
