'use client';

import React, { useEffect, useState } from 'react';
import { X, User, Mail, Phone, Building, MapPin, ShieldAlert, GraduationCap, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import Link from 'next/link';
import ProvisionInstituteAdminModal from './ProvisionInstituteAdminModal';
import UpdateInstituteModal from './UpdateInstituteModal';
import { PermissionGuard } from '@/features/auth/guards';
import { PERMISSIONS } from '@/constants/permissions';

interface DrawerProps {
  institute: {
    id: string;
    name: string;
    code: string;
    sectorId?: string; 
    address: string | null;
    contactPerson: string | null;
    contactMobile: string | null;
    contactEmail: string | null;
    isActive: boolean;
    districtSector: {
      id: string;
      name: string;
      district: {
        id: string;
        name: string;
      };
      sector: {
        id: string;
        name: string;
      };
    };
    instituteAdmin?: {
      user: {
        id: string;
        firstName: string;
        lastName: string;
        email: string;
        phone: string | null;
        isActive: boolean;
      };
    } | null;
    _count: {
      careerAdvisors: number;
      students: number;
    };
  };
  onClose: () => void;
}

export default function InstituteAccessManagementDrawer({ institute, onClose }: DrawerProps) {
  const [provisionTarget, setProvisionTarget] = useState<any | null>(null);
  const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false);
  const [isMounted, setIsMounted] = useState(false);

  console.log("INSTITUTE:", institute)

  useEffect(() => {
    setIsMounted(true);
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, []);

  const handleSafeClose = () => {
    setIsMounted(false);
    setTimeout(() => {
      onClose();
    }, 250);
  };

  // Safe runtime resolution pattern for database includes tracking
  const adminUser = institute.instituteAdmin?.user;

  return (
    <>
      {/* Backdrop Fog Overlay */}
      <div 
        className={`fixed inset-0 bg-black/40 backdrop-blur-xs z-40 transition-opacity duration-300 ease-in-out ${
          isMounted ? 'opacity-100' : 'opacity-0'
        }`} 
        onClick={handleSafeClose} 
      />

      {/* Slide-out Panel Wrapper */}
      <div 
        className={`fixed right-0 top-0 bottom-0 w-full max-w-xl bg-background border-l border-border shadow-2xl z-50 p-6 flex flex-col justify-between transform transition-transform duration-300 ease-in-out ${
          isMounted ? 'translate-x-0' : 'translate-x-full'
        } select-none`}
      >
        <div className="space-y-5 flex-1 overflow-y-auto pr-1">
          <div className="flex items-center justify-between border-b border-border/10 pb-4">
            <div className="flex items-center gap-2.5">
              <div className="h-9 w-9 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-[10px] font-black text-primary font-mono tracking-tighter">
                {institute.code.slice(-3)}
              </div>
              <div className="flex flex-col text-left">
                <h2 className="text-sm font-bold text-foreground leading-tight">Manage Workspace Nodes</h2>
                <span className="text-[10px] text-muted-foreground font-medium">Configure configurations, check indicators, or change administrator nodes</span>
              </div>
            </div>
            <button onClick={handleSafeClose} className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground/70 hover:text-foreground transition-colors cursor-pointer">
              <X className="h-4 w-4" />
            </button>
          </div>

          {/* Quick-Stats Panel */}
          <div className="grid grid-cols-2 gap-2 bg-muted/20 border border-border/30 p-3 rounded-xl text-left">
            <div className="p-2 bg-background border border-border/40 rounded-lg shadow-2xs">
              <span className="text-[10px] block font-bold text-muted-foreground/70 uppercase tracking-wide">Registered Advisors</span>
              <span className="text-xl font-black text-foreground mt-0.5 block">{institute._count?.careerAdvisors || 0}</span>
            </div>
            <div className="p-2 bg-background border border-border/40 rounded-lg shadow-2xs">
              <span className="text-[10px] block font-bold text-muted-foreground/70 uppercase tracking-wide">Monitored Students</span>
              <span className="text-xl font-black text-foreground mt-0.5 block">{institute._count?.students || 0}</span>
            </div>
          </div>

          {/* SECTION: Campus Context Metadata */}
          <div className="border border-border/40 bg-surface rounded-xl p-3.5 space-y-3 text-left shadow-xs">
          <PermissionGuard permission={PERMISSIONS.INSTITUTE_UPDATE}>
            <div className="flex items-center justify-between border-b border-border/10 pb-2">
              <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
                <Building className="h-3 w-3 text-primary" /> Campus Corporate Parameters
              </div>
              
              <Button 
                variant="outline" 
                onClick={() => setIsUpdateModalOpen(true)}
                className="h-6 text-[9px] font-bold uppercase rounded-md tracking-wider cursor-pointer"
              >
                Update Campus Parameters
              </Button>
            </div>
            </PermissionGuard>

            <div className="grid grid-cols-1 gap-y-2.5 text-xs border-t border-border/10 pt-2.5">
              <div>
                <span className="text-[10px] block text-muted-foreground/60 font-medium">Campus Nomenclature</span>
                <span className="font-bold text-foreground">{institute.name}</span>
              </div>

              <div className="grid grid-cols-2 gap-2">
                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Institutional Hub Code</span>
                  <span className="font-mono font-bold text-primary text-xs">{institute.code}</span>
                </div>
                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Topology Routing Track</span>
                  <span className="font-semibold text-foreground/90 inline-flex items-center gap-1">
                    <MapPin className="h-2.5 w-2.5 text-muted-foreground" /> {institute.districtSector?.district?.name} ({institute.districtSector?.sector?.name})
                  </span>
                </div>
              </div>

              {institute.address && (
                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Physical Delivery Description</span>
                  <span className="font-medium text-foreground/80 leading-tight block">{institute.address}</span>
                </div>
              )}
            </div>
          </div>

          {/* 🌟 NEW SUBSECTION: PRIMARY POINT OF CONTACT METADATA GRID */}
          <div className="border border-border/40 bg-surface rounded-xl p-3.5 space-y-3 text-left shadow-xs">
            <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground border-b border-border/10 pb-2">
              <ShieldCheck className="h-3.5 w-3.5 text-primary" /> Primary Campus Contacts (POC)
            </div>

            <div className="grid grid-cols-1 gap-y-2.5 text-xs">
              <div>
                <span className="text-[10px] block text-muted-foreground/60 font-medium">Contact Officer Name</span>
                <span className="font-bold text-foreground flex items-center gap-2">
                  <User className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />
                  <span>{institute.contactPerson || '—'}</span>
                </span>
              </div>

              <div className="grid grid-cols-2 gap-2">
                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Corporate Communication Email</span>
                  <span className="font-mono font-medium text-foreground/90 truncate block flex items-center gap-1.5" title={institute.contactEmail || undefined}>
                    <Mail className="h-3 w-3 text-muted-foreground/50 shrink-0" />
                    <span>{institute.contactEmail || '—'}</span>
                  </span>
                </div>
                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Direct Telephone Line</span>
                  <span className="font-mono font-medium text-foreground/90 flex items-center gap-1.5">
                    <Phone className="h-3 w-3 text-muted-foreground/50 shrink-0" />
                    <span>{institute.contactMobile || '—'}</span>
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Connected Admin Node Account Section */}
          <div className="border border-border/40 bg-surface rounded-xl p-3.5 space-y-3 text-left shadow-xs">
            <div className="flex items-center justify-between border-b border-border/10 pb-2">
              <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
                <GraduationCap className="h-3.5 w-3.5 text-primary" /> Connected Administrative Node
              </div>
            </div>

            {adminUser ? (
              <div className="space-y-2.5 pt-1">
                <div className="flex items-center gap-2 text-xs font-semibold text-foreground">
                  <User className="h-3.5 w-3.5 text-muted-foreground/60" />
                  <span>{adminUser.firstName} {adminUser.lastName}</span>
                </div>
                <div className="flex items-center gap-2 text-[11px] font-mono text-muted-foreground/80">
                  <Mail className="h-3.5 w-3.5 text-muted-foreground/60" />
                  <span>{adminUser.email}</span>
                </div>
                {adminUser.phone && (
                  <div className="flex items-center gap-2 text-[11px] font-mono text-muted-foreground/80">
                    <Phone className="h-3.5 w-3.5 text-muted-foreground/60" />
                    <span>{adminUser.phone}</span>
                  </div>
                )}
              </div>
            ) : (
              <div className="text-center py-4 bg-amber-500/5 border border-dashed border-amber-500/20 rounded-xl flex flex-col items-center justify-center gap-2">
                <ShieldAlert className="h-5 w-5 text-amber-500" />
                <div className="text-center">
                  <p className="text-xs font-bold text-amber-500">Ownership Node Unlinked</p>
                  <p className="text-[10px] text-muted-foreground/70 max-w-xs mt-0.5">No administrative profile is mapped to this environment tracks framework.</p>
                </div>
                
                <Button onClick={() => setProvisionTarget(institute)} size="sm" className="h-7 text-[10px] font-bold bg-amber-500 text-white hover:bg-amber-600 rounded-md cursor-pointer">
                  Provision Authority Profile
                </Button>
              </div>
            )}
          </div>
        </div>

        <div className="border-t border-border/10 pt-4 flex items-center justify-end">
          <Button variant="ghost" onClick={handleSafeClose} className="h-8 text-xs font-semibold cursor-pointer">
            Close Panel
          </Button>
        </div>
      </div>

      {/* MODAL 1: Account Connection Profile Mapping */}
      {provisionTarget && (
        <ProvisionInstituteAdminModal
          institute={{
            id: provisionTarget.id,
            name: provisionTarget.name,
            code: provisionTarget.code,
            sectorId: provisionTarget.sectorId || provisionTarget.sector?.id || '', 
            address: provisionTarget.address,
            contactPerson: provisionTarget.contactPerson,
            contactMobile: provisionTarget.contactMobile,
            contactEmail: provisionTarget.contactEmail,
          }}
          onClose={() => setProvisionTarget(null)}
        />
      )}

      {/* MODAL 2: Dynamic Update Payload Assignment Configuration */}
      {isUpdateModalOpen && (
        <UpdateInstituteModal
          institute={{
            id: institute.id,
            name: institute.name,
            code: institute.code,
            sectorId: institute.sectorId || institute.districtSector?.sector?.id || '',
            address: institute.address,
            contactPerson: institute.contactPerson,
            contactMobile: institute.contactMobile,
            contactEmail: institute.contactEmail,
            isActive: institute.isActive
          }}
          onClose={() => setIsUpdateModalOpen(false)}
        />
      )}
    </>
  );
}