'use client';

import React, { useEffect, useState } from 'react';
import { X, Layers, RefreshCw, CheckCircle2, XCircle, MapPin, User, Mail, Trash2, Edit3, Building, FileText, Phone, Compass, Tag } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useToggleAssignmentStatus, useDeleteAssignment } from '@/services/district-sector-assignments/queries';
import BulkAssignModal from './BulkAssignModal';
import TransferOwnershipModal from './TransferOwnershipModal';
import ConfirmationDialog from '@/components/ui/confirmationDialog';
import Link from 'next/link';

interface DrawerProps {
  user: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    phone?: string | null;
    isActive: boolean;
    userProfile?: {
      id: string;
      organizationName?: string | null;
      registeredOfficeAddress?: string | null;
      city?: string | null;
      state?: string | null;
      postalCode?: string | null;
      country?: string | null;
      taxIdentifier?: string | null;
      corporateRegNumber?: string | null;
      officialLandline?: string | null;
    } | null;
    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 };
      };
    }>;
  };
  districtsList: any[];
  onClose: () => void;
}

export default function OwnerAccessManagementDrawer({ user, districtsList, onClose }: DrawerProps) {
  const toggleStatusMutation = useToggleAssignmentStatus();
  const deleteAssignmentMutation = useDeleteAssignment();
  
  const [isBulkOpen, setIsBulkOpen] = useState(false);
  const [isTransferOpen, setIsTransferOpen] = useState(false);
  const [isMounted, setIsMounted] = useState(false);

  const [confirmDeleteTarget, setConfirmDeleteTarget] = useState<{ id: string; name: string } | null>(null);

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

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

  const executePermanentDeletion = async () => {
    if (!confirmDeleteTarget) return;
    try {
      await deleteAssignmentMutation.mutateAsync(confirmDeleteTarget.id);
      setConfirmDeleteTarget(null);
    } catch (e) {
      // Handled internally by mutation hooks
    }
  };

  const activeAssignments = user.districtSectorOwner.filter(a => a.isActive);
  const revokedAssignments = user.districtSectorOwner.filter(a => !a.isActive);

  // Extract unique assigned District and Sector names for quick badge view
  const assignedDistricts = Array.from(
    new Set(activeAssignments.map((a) => a.districtSector?.district?.name).filter(Boolean))
  );
  const assignedSectors = Array.from(
    new Set(activeAssignments.map((a) => a.districtSector?.sector?.name).filter(Boolean))
  );

  return (
    <>
      {/* Backdrop Fog Overlay Canvas */}
      <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} 
      />

      {/* Hardware-Accelerated Sliding Panel Container */}
      <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`}
      >
        {/* Main Scrolling Workspace Section */}
        <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-sm font-black text-primary">
                {user.firstName[0]}{user.lastName[0]}
              </div>
              <div className="flex flex-col text-left">
                <h2 className="text-sm font-bold text-foreground leading-tight">Manage Jurisdiction Routes</h2>
                <span className="text-[10px] text-muted-foreground">Modify active matrix points or execute state handoffs</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>

          {/* Profile Quick-Info Block with Edit Profile Button */}
          <div className="bg-surface/50 border border-border/40 rounded-xl p-3.5 flex items-center justify-between gap-4 text-left">
            <div className="space-y-2 min-w-0">
              <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 className="truncate">{user.firstName} {user.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 className="truncate">{user.email}</span>
              </div>
              {user.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>{user.phone}</span>
                </div>
              )}
            </div>

            <Link href={`/owners/edit/${user.id}`}>
              <Button 
                variant="outline" 
                size="sm" 
                className="h-8 text-[10px] font-bold gap-1 rounded-lg border-border/60 hover:bg-background shrink-0 cursor-pointer"
              >
                <Edit3 className="h-3 w-3" /> Edit Profile
              </Button>
            </Link>
          </div>

          {/* 📍 JURISDICTION & SECTOR SUMMARY BADGES */}
          <div className="border border-border/40 bg-surface/50 rounded-xl p-3.5 space-y-3 text-left">
            <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
              <Compass className="h-3 w-3 text-primary" /> Assigned Operational Bounds
            </div>

            <div className="space-y-2 text-xs">
              {/* Assigned Districts */}
              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-semibold uppercase tracking-wider mb-1">
                  Active District Jurisdictions
                </span>
                <div className="flex flex-wrap gap-1.5">
                  {assignedDistricts.length > 0 ? (
                    assignedDistricts.map((dist, idx) => (
                      <span
                        key={idx}
                        className="inline-flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-2 py-0.5 rounded-md text-[11px] font-bold"
                      >
                        <MapPin className="h-2.5 w-2.5" />
                        {dist}
                      </span>
                    ))
                  ) : (
                    <span className="text-[11px] text-muted-foreground italic">No district assignments</span>
                  )}
                </div>
              </div>

              {/* Assigned Sectors */}
              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-semibold uppercase tracking-wider mb-1">
                  Active Sectors Covered
                </span>
                <div className="flex flex-wrap gap-1.5">
                  {assignedSectors.length > 0 ? (
                    assignedSectors.map((sector, idx) => (
                      <span
                        key={idx}
                        className="inline-flex items-center gap-1 bg-muted border border-border/60 px-2 py-0.5 rounded-md text-[11px] font-semibold text-foreground"
                      >
                        <Tag className="h-2.5 w-2.5 text-muted-foreground" />
                        {sector}
                      </span>
                    ))
                  ) : (
                    <span className="text-[11px] text-muted-foreground italic">No sector assignments</span>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* CORPORATE METADATA SUMMARY SUB-PANEL BLOCK */}
          {user.userProfile && (
            <div className="border border-border/40 bg-surface/50 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">
                <Building className="h-3 w-3 text-primary" /> Verified Company Parameters
              </div>
              
              <div className="grid grid-cols-2 gap-x-4 gap-y-2.5 text-xs border-t border-border/10 pt-2.5">
                <div className="col-span-2">
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Organization Name</span>
                  <span className="font-bold text-foreground">{user.userProfile.organizationName || '—'}</span>
                </div>
                
                <div className="col-span-2">
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Registered Office Address</span>
                  <span className="font-medium text-foreground leading-tight block">
                    {user.userProfile.registeredOfficeAddress}, {user.userProfile.city}, {user.userProfile.state} - {user.userProfile.postalCode}, {user.userProfile.country}
                  </span>
                </div>

                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium flex items-center gap-1">
                    <FileText className="h-2.5 w-2.5" /> Corporate Reg (CIN)
                  </span>
                  <span className="font-mono text-[11px] font-semibold text-foreground/90">{user.userProfile.corporateRegNumber || '—'}</span>
                </div>

                <div>
                  <span className="text-[10px] block text-muted-foreground/60 font-medium flex items-center gap-1">
                    <FileText className="h-2.5 w-2.5" /> Tax ID / GSTIN
                  </span>
                  <span className="font-mono text-[11px] font-semibold text-foreground/90 truncate block" title={user.userProfile.taxIdentifier || undefined}>
                    {user.userProfile.taxIdentifier || '—'}
                  </span>
                </div>

                <div className="col-span-2">
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">Official Landline</span>
                  <span className="font-mono text-foreground">{user.userProfile.officialLandline || '—'}</span>
                </div>
              </div>
            </div>
          )}

          {/* Configuration Actions Row Panel Layout */}
          <div className="grid grid-cols-2 gap-2">
            <Button 
              variant="outline" 
              onClick={() => setIsBulkOpen(true)}
              className="h-9 rounded-lg border-indigo-500/20 bg-indigo-500/5 hover:bg-indigo-500/10 text-indigo-500 text-xs font-bold gap-1.5 transition-colors cursor-pointer"
            >
              <Layers className="h-3.5 w-3.5" /> Bulk Append Routes
            </Button>
            <Button 
              variant="outline" 
              onClick={() => setIsTransferOpen(true)}
              className="h-9 rounded-lg border-rose-500/20 bg-rose-500/5 hover:bg-rose-500/10 text-rose-500 text-xs font-bold gap-1.5 transition-colors cursor-pointer"
            >
              <RefreshCw className="h-3.5 w-3.5" /> Transfer Ownership
            </Button>
          </div>

          {/* ACTIVE ASSIGNMENTS SECTOR GRID MATRIX */}
          <div className="space-y-2 text-left pt-2">
            <span className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
              Active Map Configurations ({activeAssignments.length})
            </span>
            <div className="space-y-1.5">
              {activeAssignments.map((assign) => (
                <div key={assign.id} className="flex items-center justify-between p-2.5 bg-background border border-border rounded-xl shadow-xs gap-4">
                  <div className="flex items-center gap-3 min-w-0">
                    <div className="flex items-center gap-1 bg-muted px-2 py-0.5 rounded text-[10px] font-bold text-foreground border border-border/40 shrink-0">
                      <MapPin className="h-2.5 w-2.5 text-primary" /> {assign.districtSector.district.name}
                    </div>
                    <span className="text-xs font-medium text-foreground truncate">{assign.districtSector.sector.name}</span>
                  </div>
                  
                  <div className="flex items-center gap-1.5 shrink-0">
                    <button
                      onClick={() => toggleStatusMutation.mutate({ id: assign.id, isActive: false })}
                      disabled={toggleStatusMutation.isPending}
                      className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold bg-emerald-500/10 hover:bg-rose-500/10 text-emerald-500 hover:text-rose-500 rounded-full border border-emerald-500/10 hover:border-rose-500/10 group cursor-pointer transition-colors"
                    >
                      <CheckCircle2 className="h-2.5 w-2.5 group-hover:hidden" />
                      <XCircle className="h-2.5 w-2.5 hidden group-hover:block" />
                      <span className="group-hover:hidden">Active Route</span>
                      <span className="hidden group-hover:block">Revoke Access</span>
                    </button>

                    <button
                      onClick={() => setConfirmDeleteTarget({ id: assign.id, name: assign.districtSector.sector.name })}
                      className="p-1 rounded-lg text-muted-foreground/60 hover:text-destructive hover:bg-destructive/10 border border-transparent hover:border-destructive/10 transition-colors cursor-pointer"
                      title="Delete assignment permanently"
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                </div>
              ))}
              {activeAssignments.length === 0 && (
                <div className="text-center py-6 text-xs text-muted-foreground/60 border border-dashed border-border rounded-xl">
                  No active operational access bounds loaded
                </div>
              )}
            </div>
          </div>

          {/* HISTORICAL/REVOKED Route Logs */}
          {revokedAssignments.length > 0 && (
            <div className="space-y-2 text-left pt-2 opacity-70">
              <span className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                Revoked Permission Tracks ({revokedAssignments.length})
              </span>
              <div className="space-y-1.5">
                {revokedAssignments.map((assign) => (
                  <div key={assign.id} className="flex items-center justify-between p-2.5 bg-muted/40 border border-border/60 rounded-xl gap-4">
                    <div className="flex items-center gap-3 min-w-0 line-through decoration-muted-foreground/40">
                      <span className="text-[10px] font-bold text-muted-foreground bg-muted px-1.5 py-0.5 rounded border border-border/30 shrink-0">
                        {assign.districtSector.district.name}
                      </span>
                      <span className="text-xs font-medium text-muted-foreground truncate">{assign.districtSector.sector.name}</span>
                    </div>
                    
                    <div className="flex items-center gap-1.5 shrink-0">
                      <button
                        onClick={() => toggleStatusMutation.mutate({ id: assign.id, isActive: true })}
                        disabled={toggleStatusMutation.isPending}
                        className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold bg-muted text-muted-foreground hover:bg-emerald-500/10 hover:text-emerald-500 rounded-full border border-border hover:border-emerald-500/10 cursor-pointer transition-colors"
                      >
                        <XCircle className="h-2.5 w-2.5" />
                        <span>Re-activate</span>
                      </button>

                      <button
                        onClick={() => setConfirmDeleteTarget({ id: assign.id, name: assign.districtSector.sector.name })}
                        className="p-1 rounded-lg text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 border border-transparent hover:border-destructive/10 transition-colors cursor-pointer"
                        title="Delete assignment permanently"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Bottom Drawer Control Bar */}
        <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>

      {isBulkOpen && (
        <BulkAssignModal
          userId={user.id}
          userFullName={`${user.firstName} ${user.lastName}`}
          districtsList={districtsList}
          onClose={() => setIsBulkOpen(false)}
        />
      )}

      {isTransferOpen && (
        <TransferOwnershipModal
          userId={user.id}
          userFullName={`${user.firstName} ${user.lastName}`}
          onClose={() => setIsTransferOpen(false)}
        />
      )}

      <ConfirmationDialog
        isOpen={!!confirmDeleteTarget}
        title="Confirm Permanent Jurisdiction Removal"
        description={`Are you absolutely sure you want to permanently delete the assignment mapping for "${confirmDeleteTarget?.name}"? Doing so drops this node's monitoring track instantly and cannot be undone.`}
        confirmLabel="Wipe Route Item"
        cancelLabel="Keep Assignment"
        variant="danger"
        isLoading={deleteAssignmentMutation.isPending}
        onConfirm={executePermanentDeletion}
        onCancel={() => setConfirmDeleteTarget(null)}
      />
    </>
  );
}