'use client';

import React, { useState } from 'react';
import { Plus, Search, MapPin, CheckCircle, XCircle, UserPlus, Building, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { PermissionGuard } from '@/features/auth/guards';
import { PERMISSIONS } from '@/constants/permissions';
import { DataTable, Column } from '@/components/ui/data-table'; 
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import Link from 'next/link';
import { useInstitutes } from '@/services/institutes/queries';
import InstituteAccessManagementDrawer from './_components/InstituteAccessManagementDrawer';
import ProvisionInstituteAdminModal from './_components/ProvisionInstituteAdminModal';

// Aligned cleanly with your repository include structure payload types
interface InstituteWithAdminRow {
  id: string;
  name: string;
  code: string;
  address: string | null;
  contactPerson: string | null;
  contactMobile: string | null;
  contactEmail: string | null;
  isActive: boolean;
  createdAt: string;
  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;
  };
}

export default function InstitutesManagementPage() {
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);

  // 1. Declare local state variable at top of your page component
  const [provisionTarget, setProvisionTarget] = useState<InstituteWithAdminRow | null>(null);
  
  // Slide-out panel control layout variables
  const [activeManagementInstitute, setActiveManagementInstitute] = useState<InstituteWithAdminRow | null>(null);
  
  // Connect the client querying state to your hooks structure
  const { data, isLoading } = useInstitutes(page, search);
  const rawInstitutes: InstituteWithAdminRow[] = (data as any)?.items || [];

  console.log("rawInstitutes:", rawInstitutes)

  const columns: Column<InstituteWithAdminRow>[] = [
    {
      header: 'Code',
      className: 'w-24 font-mono font-bold text-primary tracking-tight text-xs',
      cell: (row) => row.code,
    },
    {
      header: 'Institute Workspace Node',
      className: 'font-semibold tracking-tight text-xs text-foreground min-w-[220px]',
      cell: (row) => (
        <div className="flex flex-col text-left">
          <div className="flex items-center gap-2 font-semibold text-foreground text-xs leading-tight">
            <Building className="h-3.5 w-3.5 text-muted-foreground/50 shrink-0" />
            <span>{row.name}</span>
          </div>
          {row.address && (
            <span className="text-[10px] text-muted-foreground/60 font-medium pl-5 mt-0.5 max-w-xs truncate">
              {row.address}
            </span>
          )}
        </div>
      ),
    },
    {
      header: 'Regional Topology Link',
      className: 'text-xs text-muted-foreground',
      cell: (row) => (
        <div className="flex flex-col text-left space-y-0.5">
          <div className="flex items-center gap-1 text-foreground/90 font-medium">
            <MapPin className="h-3 w-3 text-primary/70" />
            <span>{row.districtSector?.district?.name}</span>
          </div>
          <span className="text-[10px] text-muted-foreground/50 pl-4 font-mono">
            Sector: {row.districtSector?.sector?.name}
          </span>
        </div>
      ),
    },
    {
      header: 'Institute Admin Profile',
      className: 'min-w-[220px]',
      cell: (row) => {
        if (row.instituteAdmin?.user) {
          const u = row.instituteAdmin.user;
          return (
            <div className="flex items-center gap-2 group text-left">
              <div className="h-7 w-7 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center text-[10px] font-bold text-primary shrink-0">
                {u.firstName[0]}{u.lastName[0]}
              </div>
              <div className="flex flex-col min-w-0">
                <span className="text-foreground font-semibold tracking-tight text-xs leading-tight truncate">
                  {u.firstName} {u.lastName}
                </span>
                <span className="text-[10px] text-muted-foreground/60 font-medium font-mono mt-0.5 truncate">
                  {u.email}
                </span>
              </div>
            </div>
          );
        }
        return (
          <Button
            variant="outline"
            onClick={() => setProvisionTarget(row)}
            className="h-7 text-[10px] font-bold text-amber-500 hover:text-amber-600 hover:bg-amber-500/5 border border-dashed border-amber-500/20 hover:border-amber-500/40 rounded-md px-2 gap-1 cursor-pointer"
          >
            <UserPlus className="h-3 w-3 stroke-[2.5]" />
            <span>Link Account</span>
          </Button>
        );
      },
    },
    {
      header: 'Counters',
      className: 'w-32 text-left hidden md:table-cell',
      cell: (row) => (
        <div className="flex flex-col text-left text-[10px] font-semibold text-muted-foreground/70 space-y-0.5">
          <span>Advisors: <strong className="text-foreground">{row._count?.careerAdvisors || 0}</strong></span>
          <span>Students: <strong className="text-foreground">{row._count?.students || 0}</strong></span>
        </div>
      )
    },
    {
      header: 'Status',
      className: 'w-24',
      cell: (row) => row.isActive ? (
        <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/10">
          <CheckCircle className="h-2.5 w-2.5" /> Active
        </span>
      ) : (
        <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-rose-500/10 text-rose-500 border border-rose-500/10">
          <XCircle className="h-2.5 w-2.5" /> Inactive
        </span>
      ),
    },
    {
      header: 'Matrix Controls',
      className: 'text-right w-24',
      cell: (row) => (
        <Button 
          variant="outline" 
          onClick={() => setActiveManagementInstitute(row)}
          className="h-7 text-[10px] font-bold rounded-md px-2 gap-1 shadow-sm transition-all bg-surface text-foreground hover:bg-surface/90 cursor-pointer"
        >
          <span>Manage</span>
          <ChevronRight className="h-3 w-3 stroke-[2.5]" />
        </Button>
      )
    }
  ];

  if (isLoading) return <TableSkeleton />;

  return (
    <>
      <div className="space-y-4 max-w-7xl mx-auto animate-in fade-in duration-300 select-none">
        {/* TITLE PANEL VIEW HEADER */}
        <div className="flex items-center justify-between border-b border-border/10 pb-4">
          <div className="space-y-0.5">
            <h1 className="text-sm font-black tracking-widest text-foreground uppercase">Managed Institutes Matrix</h1>
            <p className="text-[11px] font-medium text-muted-foreground/70">Configure corporate campus configurations, link sectors, and manage permissions infrastructure profiles.</p>
          </div>
          <PermissionGuard permission={PERMISSIONS.MASTERS_INSTITUTES_MANAGE || PERMISSIONS.MASTERS_DISTRICTS_MANAGE}>
            <Link href="/institutes/new">
              <Button className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase shadow-sm gap-1.5 transition-all bg-foreground text-background hover:bg-foreground/90 cursor-pointer">
                <Plus className="h-3.5 w-3.5 stroke-[2.5]" /> Provision New Campus
              </Button>
            </Link>
          </PermissionGuard>
        </div>

        {/* SEARCH BAR BUS CONTAINER */}
        <div className="flex flex-wrap items-center gap-2">
          <div className="flex items-center max-w-xs w-full relative group">
            <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground/60 transition-colors group-focus-within:text-primary" />
            <input 
              type="text" 
              placeholder="Search campuses by profile variables..." 
              value={search} 
              onChange={(e) => { setSearch(e.target.value); setPage(1); }}
              className="w-full text-xs font-medium pl-8 pr-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
            />
          </div>
        </div>

        {/* REUSABLE DATATABLE MATRIX COMPONENT */}
        <DataTable 
          data={rawInstitutes} 
          columns={columns} 
          emptyMessage="No administrative campus locations found matching your criteria properties."
          pagination={data ? {
            page: data.page,
            pages: data.pages,
            total: data.total,
            onPageChange: setPage
          } : undefined}
        />
      </div>

      {/* Slide-out Panel Overlay Render */}
      {activeManagementInstitute && (
        <InstituteAccessManagementDrawer
          institute={activeManagementInstitute}
          onClose={() => setActiveManagementInstitute(null)}
        />
      )}

      {provisionTarget && (
        <ProvisionInstituteAdminModal
          institute={{
            id: provisionTarget.id,
            name: provisionTarget.name,
            code: provisionTarget.code,
            sectorId: provisionTarget.districtSector.sector.id,
            address: provisionTarget.address,
            contactPerson: provisionTarget.contactPerson,
            contactMobile: provisionTarget.contactMobile,
            contactEmail: provisionTarget.contactEmail,
          }}
          onClose={() => setProvisionTarget(null)}
        />
      )}
    </>
  );
}