import React, { useState } from 'react';
import { 
  Search, 
  Plus, 
  Download, 
  Upload, 
  Edit, 
  MoreHorizontal, 
  FileText,
  MapPin,
  Shield,
  Bell,
  Check,
  X
} from 'lucide-react';
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import { Label } from "../ui/label";
import { Switch } from "../ui/switch";
import { Badge } from "../ui/badge";
import { Checkbox } from "../ui/checkbox";
import { ScrollArea } from "../ui/scroll-area";
import { cn } from "../ui/utils";

// --- Mock Data ---

const MOCK_LOCATIONS = [
  { id: '1', name: 'Downtown Store (101)' },
  { id: '2', name: 'Uptown Store (102)' },
  { id: '3', name: 'Airport Kiosk (201)' },
  { id: '4', name: 'Mall Outlet (305)' },
];

const MOCK_ROLES = [
  { 
    id: 'r1', 
    name: 'Partner Admin', 
    permissions: ['all'], 
    notifications: ['system_updates', 'billing'] 
  },
  { 
    id: 'r2', 
    name: 'Group Admin', 
    permissions: ['manage_users', 'manage_products', 'view_reports'], 
    notifications: ['new_users'] 
  },
  { 
    id: 'r3', 
    name: 'Manager', 
    permissions: ['manage_store', 'view_reports', 'manage_inventory'], 
    notifications: ['label_expiry', 'low_stock'] 
  },
  { 
    id: 'r4', 
    name: 'Team Member', 
    permissions: ['view_tasks', 'print_labels'], 
    notifications: ['task_assignment'] 
  }
];

const MOCK_PARTNERS = [
  { id: 'p1', name: 'Global Foods Inc.', status: 'active', contact: 'admin@globalfoods.com' },
  { id: 'p2', name: 'Local Eateries Co.', status: 'active', contact: 'support@localeateries.com' },
];

const MOCK_GROUPS = [
  { id: 'g1', name: 'West Coast Region', partner: 'Global Foods Inc.', status: 'active' },
  { id: 'g2', name: 'East Coast Region', partner: 'Global Foods Inc.', status: 'inactive' },
];

const MOCK_MEMBERS = [
  { 
    id: 'm1', 
    name: 'Alice Johnson', 
    role: 'Manager', 
    locations: ['Downtown Store (101)', 'Uptown Store (102)'], 
    email: 'alice@example.com',
    status: 'active'
  },
  { 
    id: 'm2', 
    name: 'Bob Smith', 
    role: 'Team Member', 
    locations: ['Airport Kiosk (201)'], 
    email: 'bob@example.com',
    status: 'active'
  },
  { 
    id: 'm3', 
    name: 'Charlie Brown', 
    role: 'Team Member', 
    locations: ['Downtown Store (101)'], 
    email: 'charlie@example.com',
    status: 'inactive'
  },
];

// --- Types ---
type ViewTab = 'Roles' | 'Partner' | 'Group' | 'Team Member';

export function PeopleView() {
  const [activeTab, setActiveTab] = useState<ViewTab>('Roles');
  
  // Data States
  const [roles, setRoles] = useState(MOCK_ROLES);
  const [partners, setPartners] = useState(MOCK_PARTNERS);
  const [groups, setGroups] = useState(MOCK_GROUPS);
  const [members, setMembers] = useState(MOCK_MEMBERS);

  // Dialog States
  const [isRoleDialogOpen, setIsRoleDialogOpen] = useState(false);
  const [isPartnerDialogOpen, setIsPartnerDialogOpen] = useState(false);
  const [isGroupDialogOpen, setIsGroupDialogOpen] = useState(false);
  const [isMemberDialogOpen, setIsMemberDialogOpen] = useState(false);

  // Handlers
  const handleExportPdf = () => {
    alert(`Exporting ${activeTab} list to PDF...`);
  };

  const openCreateDialog = () => {
    switch (activeTab) {
      case 'Roles': setIsRoleDialogOpen(true); break;
      case 'Partner': setIsPartnerDialogOpen(true); break;
      case 'Group': setIsGroupDialogOpen(true); break;
      case 'Team Member': setIsMemberDialogOpen(true); break;
    }
  };

  const renderToolbar = () => {
    const canBulkOps = activeTab === 'Team Member';
    return (
      <div className="flex flex-wrap items-center gap-2 py-4 bg-gray-50">
        <Input
          placeholder="Search"
          className="border border-black rounded-lg h-9 w-64 bg-white text-black"
        />
        <div className="flex-1" />
        {canBulkOps && (
          <>
            <Button variant="outline" className="h-9 border border-black rounded-lg text-black px-4 bg-white hover:bg-gray-50">
              Bulk Import
            </Button>
            <Button variant="outline" className="h-9 border border-black rounded-lg text-black px-4 bg-white hover:bg-gray-50">
              Bulk Edit
            </Button>
          </>
        )}
        <Button variant="outline" onClick={handleExportPdf} className="h-9 border border-black rounded-lg text-black px-4 bg-white hover:bg-gray-50">
          Bulk Export (PDF)
        </Button>
        <Button
          className="h-9 bg-blue-600 hover:bg-blue-700 text-white rounded-lg px-6 font-medium border-0"
          onClick={openCreateDialog}
        >
          New+
        </Button>
      </div>
    );
  };

  const renderContent = () => {
    switch (activeTab) {
      case 'Roles':
        return (
          <Table>
            <TableHeader>
              <TableRow className="bg-gray-100">
                <TableHead className="font-bold text-black border-r">Role Name</TableHead>
                <TableHead className="font-bold text-black border-r">Access Permissions</TableHead>
                <TableHead className="font-bold text-black border-r">Notifications</TableHead>
                <TableHead className="font-bold text-black text-center">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {roles.map(role => (
                <TableRow key={role.id}>
                  <TableCell className="font-medium border-r">{role.name}</TableCell>
                  <TableCell className="border-r">
                    <div className="flex flex-wrap gap-1">
                      {role.permissions.map(p => (
                        <Badge key={p} variant="secondary" className="text-xs rounded-lg bg-blue-100 text-blue-800 hover:bg-blue-100">{p}</Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell className="border-r">
                    <div className="flex flex-wrap gap-1">
                      {role.notifications.map(n => (
                        <Badge key={n} variant="outline" className="text-xs rounded-lg border-orange-200 text-orange-700 bg-orange-50">{n}</Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell className="text-center">
                    <Button variant="ghost" size="sm" className="rounded-lg"><Edit className="w-4 h-4 text-gray-500" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        );
      
      case 'Partner':
        return (
          <Table>
             <TableHeader>
              <TableRow className="bg-gray-100">
                <TableHead className="font-bold text-black border-r">Partner Name</TableHead>
                <TableHead className="font-bold text-black border-r">Contact</TableHead>
                <TableHead className="font-bold text-black border-r">Status</TableHead>
                <TableHead className="font-bold text-black text-center">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {partners.map(p => (
                <TableRow key={p.id}>
                  <TableCell className="font-medium border-r">{p.name}</TableCell>
                  <TableCell className="border-r">{p.contact}</TableCell>
                  <TableCell className="border-r">
                    <Badge className={cn("rounded-lg", p.status === 'active' ? "bg-green-600" : "bg-gray-400")}>
                      {p.status}
                    </Badge>
                  </TableCell>
<TableCell className="text-center">
                    <Button variant="ghost" size="sm" className="rounded-lg"><Edit className="w-4 h-4 text-gray-500" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        );
      
      case 'Group':
        return (
          <Table>
             <TableHeader>
              <TableRow className="bg-gray-100">
                <TableHead className="font-bold text-black border-r">Group Name</TableHead>
                <TableHead className="font-bold text-black border-r">Parent Partner</TableHead>
                <TableHead className="font-bold text-black border-r">Status</TableHead>
                <TableHead className="font-bold text-black text-center">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {groups.map(g => (
                <TableRow key={g.id}>
                  <TableCell className="font-medium border-r">{g.name}</TableCell>
                  <TableCell className="border-r">{g.partner}</TableCell>
                  <TableCell className="border-r">
                    <Badge className={cn("rounded-lg", g.status === 'active' ? "bg-green-600" : "bg-gray-400")}>
                      {g.status}
                    </Badge>
                  </TableCell>
<TableCell className="text-center">
                    <Button variant="ghost" size="sm" className="rounded-lg"><Edit className="w-4 h-4 text-gray-500" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        );
      
      case 'Team Member':
        return (
          <Table>
             <TableHeader>
              <TableRow className="bg-gray-100">
                <TableHead className="font-bold text-black border-r">Name</TableHead>
                <TableHead className="font-bold text-black border-r">Email</TableHead>
                <TableHead className="font-bold text-black border-r">Role</TableHead>
                <TableHead className="font-bold text-black border-r">Assigned Locations</TableHead>
                <TableHead className="font-bold text-black border-r">Status</TableHead>
                <TableHead className="font-bold text-black text-center">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {members.map(m => (
                <TableRow key={m.id}>
                  <TableCell className="font-medium border-r">{m.name}</TableCell>
                  <TableCell className="border-r text-gray-600">{m.email}</TableCell>
                  <TableCell className="border-r">
                    <Badge variant="outline" className="font-normal rounded-lg">{m.role}</Badge>
                  </TableCell>
                  <TableCell className="border-r">
                    <div className="flex flex-col gap-1">
                      {m.locations.map(loc => (
                        <div key={loc} className="flex items-center gap-1 text-xs text-gray-600">
                          <MapPin className="w-3 h-3" /> {loc}
                        </div>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell className="border-r">
                    <Badge className={cn("rounded-lg", m.status === 'active' ? "bg-green-600" : "bg-gray-400")}>
                      {m.status}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <Button variant="ghost" size="sm" className="rounded-lg"><Edit className="w-4 h-4 text-gray-500" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        );
    }
  };

  return (
    <div className="h-full flex flex-col bg-white">
      {renderToolbar()}

      <div className="flex-1 overflow-auto bg-gray-50">
        {/* 标签与表格融合在一个圆角框内 */}
        <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
          <div className="flex border-b border-gray-200 bg-gray-50/50">
            {['Roles', 'Partner', 'Group', 'Team Member'].map((tab) => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab as ViewTab)}
                className={cn(
                  "px-6 py-3 text-sm font-medium transition-colors rounded-t-lg",
                  activeTab === tab
                    ? "bg-white text-black font-bold border border-b-0 border-gray-200 shadow-sm relative -mb-px"
                    : "text-gray-500 hover:bg-gray-100 hover:text-gray-700"
                )}
              >
                {tab}
              </button>
            ))}
          </div>
          <div className="min-h-[200px]">
            {renderContent()}
          </div>
        </div>
      </div>

      {/* --- Dialogs --- */}
      <CreateRoleDialog open={isRoleDialogOpen} onOpenChange={setIsRoleDialogOpen} />
      <CreatePartnerDialog open={isPartnerDialogOpen} onOpenChange={setIsPartnerDialogOpen} />
      <CreateGroupDialog open={isGroupDialogOpen} onOpenChange={setIsGroupDialogOpen} />
      <CreateMemberDialog open={isMemberDialogOpen} onOpenChange={setIsMemberDialogOpen} roles={roles} />
    </div>
  );
}

// --- Sub-Components (Dialogs) ---

function CreateRoleDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>Create New Role</DialogTitle>
          <DialogDescription>Define permissions and notification settings for this role.</DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Role Name</Label>
            <Input placeholder="e.g. Inventory Specialist" />
          </div>
          
          <div className="space-y-3">
            <Label className="flex items-center gap-2"><Shield className="w-4 h-4" /> Access Permissions</Label>
            <div className="grid grid-cols-2 gap-2 p-3 bg-gray-50 rounded border border-gray-100">
              {['Manage Labels', 'Manage Products', 'Manage People', 'View Reports', 'Edit Settings', 'Approve Batches'].map(perm => (
                <div key={perm} className="flex items-center space-x-2">
                  <Checkbox id={`perm-${perm}`} />
                  <label htmlFor={`perm-${perm}`} className="text-sm font-medium leading-none cursor-pointer">{perm}</label>
                </div>
              ))}
            </div>
          </div>

          <div className="space-y-3">
            <Label className="flex items-center gap-2"><Bell className="w-4 h-4" /> Notifications (Alerts)</Label>
            <div className="grid grid-cols-1 gap-2 p-3 bg-gray-50 rounded border border-gray-100">
              <div className="flex items-center space-x-2">
                <Checkbox id="notif-expiry" defaultChecked />
                <label htmlFor="notif-expiry" className="text-sm font-medium leading-none cursor-pointer">Label Expiry Alerts</label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox id="notif-stock" />
                <label htmlFor="notif-stock" className="text-sm font-medium leading-none cursor-pointer">Low Stock Alerts</label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox id="notif-tasks" />
                <label htmlFor="notif-tasks" className="text-sm font-medium leading-none cursor-pointer">New Task Assignments</label>
              </div>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={() => onOpenChange(false)} className="bg-blue-600 text-white hover:bg-blue-700">Save Role</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function CreatePartnerDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New Partner</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Partner Name</Label>
            <Input placeholder="Company Name" />
          </div>
          <div className="space-y-2">
            <Label>Contact Email</Label>
            <Input placeholder="admin@partner.com" />
          </div>
          <div className="flex items-center gap-2">
            <Switch id="partner-status" defaultChecked />
            <Label htmlFor="partner-status">Active</Label>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={() => onOpenChange(false)} className="bg-blue-600 text-white hover:bg-blue-700">Save Partner</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function CreateGroupDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New Group</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Group Name</Label>
            <Input placeholder="e.g. West Coast Region" />
          </div>
          <div className="space-y-2">
            <Label>Assign to Partner</Label>
            <Select>
              <SelectTrigger><SelectValue placeholder="Select Partner" /></SelectTrigger>
              <SelectContent>
                {MOCK_PARTNERS.map(p => <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>
          <div className="flex items-center gap-2">
            <Switch id="group-status" defaultChecked />
            <Label htmlFor="group-status">Active</Label>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={() => onOpenChange(false)} className="bg-blue-600 text-white hover:bg-blue-700">Save Group</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function CreateMemberDialog({ open, onOpenChange, roles }: { open: boolean; onOpenChange: (open: boolean) => void; roles: any[] }) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Add Team Member / Manager</DialogTitle>
          <DialogDescription>Create a user account and assign them to locations.</DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Full Name</Label>
              <Input placeholder="John Doe" />
            </div>
             <div className="space-y-2">
              <Label>Role</Label>
              <Select>
                <SelectTrigger><SelectValue placeholder="Select Role" /></SelectTrigger>
                <SelectContent>
                  {roles.map(r => <SelectItem key={r.id} value={r.name}>{r.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div className="space-y-2">
            <Label>Email Address</Label>
            <Input type="email" placeholder="john@example.com" />
          </div>

          <div className="space-y-2">
            <Label>Assign Locations (Multiple)</Label>
            <ScrollArea className="h-[120px] w-full border rounded-md p-2">
              <div className="space-y-2">
                {MOCK_LOCATIONS.map(loc => (
                  <div key={loc.id} className="flex items-center space-x-2">
                    <Checkbox id={`loc-${loc.id}`} />
                    <label htmlFor={`loc-${loc.id}`} className="text-sm cursor-pointer w-full hover:bg-gray-50 p-1 rounded">
                      {loc.name}
                    </label>
                  </div>
                ))}
              </div>
            </ScrollArea>
            <p className="text-xs text-gray-500">* Users must be assigned to at least one location.</p>
          </div>

          <div className="flex items-center gap-2">
            <Switch id="member-status" defaultChecked />
            <Label htmlFor="member-status">Active Account</Label>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={() => onOpenChange(false)} className="bg-blue-600 text-white hover:bg-blue-700">Create User</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
