'use client';

import React, { useState } from 'react';
import { Layers, RefreshCw, Plus, Search, ShieldCheck, ShieldAlert, ChevronRight } from 'lucide-react';
import { useDisctrictSectorOwner } from '@/services/district-sector-assignments/queries';
import { DataTable, Column } from '@/components/ui/data-table';
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import { Button } from '@/components/ui/button';
import { useAllDistricts } from '@/services/districts/queries';
import OwnerAccessManagementDrawer from './_components/OwnerAccessManagementDrawer';
import Link from 'next/link';

interface UserOwnerRow {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  isActive: boolean;
  createdAt: string;
  districtSectorOwner: Array<{
    id: string;
    isActive: boolean;
    districtSector: {
      id: string;
      isActive: boolean;
      district: { id: string; name: string; code: string };
      sector: { id: string; name: string; code: string };
    };
  }>;
}

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

  const [activeManagementUser, setActiveManagementManagementUser] = useState<UserOwnerRow | null>(null);

  const { data: ownersData, isLoading } = useDisctrictSectorOwner(page, search, selectedDistrict);
  const { data: districtsData } = useAllDistricts();

  const rawOwners: UserOwnerRow[] = ownersData?.items || [];
  const rawDistricts = (districtsData as any)?.items || districtsData || [];

  console.log("OWNERS:", rawOwners)

  const columns: Column<UserOwnerRow>[] = [
    {
      header: 'Governance Profile Node',
      cell: (row) => (
        <div className="flex items-center gap-3 text-left">
          <div className="h-8 w-8 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center text-xs font-bold text-primary shrink-0">
            {row.firstName[0]}{row.lastName[0]}
          </div>
          <div className="flex flex-col">
            <span className="font-semibold text-foreground text-xs leading-tight">
              {row.firstName} {row.lastName}
            </span>
            <span className="text-[10px] text-muted-foreground/70 font-mono mt-0.5">{row.email}</span>
          </div>
        </div>
      )
    },
    {
      header: 'Jurisdiction Coverage Summary',
      cell: (row) => (
        <div className="flex flex-wrap gap-1.5 items-center max-w-xl">
          {row.districtSectorOwner?.slice(0, 3).map((assign) => {
            // FIXED: Safely access nested district & sector objects from districtSector
            const district = assign.districtSector?.district;
            const sector = assign.districtSector?.sector;

            return (
              <span 
                key={assign.id} 
                className={`inline-flex items-center gap-1 text-[10px] font-medium px-2 py-0.5 rounded border ${
                  assign.isActive 
                    ? 'bg-background text-foreground border-border' 
                    : 'bg-muted/50 text-muted-foreground/60 border-dashed border-border/40 line-through'
                }`}
              >
                <span className="font-bold text-primary">{district?.code || district?.name}</span>
                <span className="text-muted-foreground/40">/</span>
                <span>{sector?.name}</span>
              </span>
            );
          })}
          {row.districtSectorOwner?.length > 3 && (
            <span className="text-[10px] font-bold text-muted-foreground/70 bg-muted px-1.5 py-0.5 rounded">
              +{row.districtSectorOwner.length - 3} more routes
            </span>
          )}
          {(!row.districtSectorOwner || row.districtSectorOwner.length === 0) && (
            <span className="text-[10px] font-medium text-amber-500 italic">No permission paths routed</span>
          )}
        </div>
      )
    },
    {
      header: 'Account Status',
      className: 'w-32',
      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">
          <ShieldCheck className="h-3 w-3" /> Operational
        </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">
          <ShieldAlert className="h-3 w-3" /> Blocked
        </span>
      )
    },
    {
      header: 'Matrix Controls',
      className: 'text-right w-36',
      cell: (row) => (
        <Button 
          variant="outline" 
          onClick={() => setActiveManagementManagementUser(row)}
          className="h-7 text-[10px] font-bold rounded-md px-2.5 gap-1 shadow-sm transition-all bg-surface text-foreground hover:bg-surface/90 cursor-pointer"
        >
          <span>Manage Access</span>
          {/* FIXED: Removed broken text/spacing classes causing structural jumps */}
          <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">Cross-Reference Matrix</h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">Manage multidirectional cross-permissions mapping districts to business sectors.</p>
        </div>

        <Link href="/owners/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]" /> New District-Sector Owner
          </Button>
        </Link>
      </div>

      {/* Unified Filter Bar */}
      <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 owners by name or email..." 
            value={search} 
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            className="w-full text-xs font-medium pl-8 pr-8 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
          />
        </div>

        <div className="w-full sm:w-auto">
          <select
            value={selectedDistrict}
            onChange={(e) => { setSelectedDistrict(e.target.value); setPage(1); }}
            className="w-full sm:w-auto text-xs font-semibold px-2.5 py-2 border border-border/40 bg-surface rounded-lg text-muted-foreground focus:outline-none focus:border-primary transition-colors cursor-pointer"
          >
            <option value="">All Maharashtra Districts</option>
            {rawDistricts.map((d: any) => (
              <option key={d.id} value={d.id}>{d.name}</option>
            ))}
          </select>
        </div>
      </div>

      <DataTable
        data={rawOwners}
        columns={columns}
        emptyMessage="No administrative profile nodes registered matching criteria."
        pagination={ownersData ? {
          page: ownersData.page,
          pages: ownersData.pages,
          total: ownersData.total,
          onPageChange: setPage
        } : undefined}
      />

    </div>
      {/* Slide-out Management Panel */}
      {activeManagementUser && (
        <OwnerAccessManagementDrawer
          user={activeManagementUser}
          districtsList={rawDistricts}
          onClose={() => setActiveManagementManagementUser(null)}
        />
      )}
      </>
  );
}