'use client';

import { useState, useEffect, useCallback } from 'react';
import { UsersRound, Plus, Trash2, Pencil, UserPlus, Key, Shield, Mail, CheckCircle, XCircle } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm';

interface Team { id: string; name: string; description: string; members: TeamMember[]; }
interface TeamMember { id: string; name: string; email: string; role: string; permissions: string[]; teamId: string; }

const TASK_PERMISSIONS = [
  { key: 'manage_users', label: 'Manage Users', desc: 'Create, edit, delete users' },
  { key: 'manage_listings', label: 'Manage Listings', desc: 'Create, edit, delete listings' },
  { key: 'manage_orders', label: 'Manage Orders', desc: 'Update order status' },
  { key: 'manage_mcq', label: 'Manage MCQ', desc: 'Add, edit, delete questions' },
  { key: 'manage_community', label: 'Moderate Community', desc: 'Approve, delete posts' },
  { key: 'send_notifications', label: 'Send Notifications', desc: 'Send push notifications' },
  { key: 'view_analytics', label: 'View Analytics', desc: 'View dashboard & stats' },
  { key: 'manage_menus', label: 'Manage Menus', desc: 'Edit navigation menus' },
  { key: 'manage_settings', label: 'Manage Settings', desc: 'Edit app settings' },
  { key: 'full_access', label: 'Full Access', desc: 'All permissions' },
];

export function AdminTeams() {
  const [teams, setTeams] = useState<Team[]>([]);
  const [loading, setLoading] = useState(true);
  const [showTeamDialog, setShowTeamDialog] = useState(false);
  const [showMemberDialog, setShowMemberDialog] = useState(false);
  const [showPermDialog, setShowPermDialog] = useState(false);
  const [editTeam, setEditTeam] = useState<Team | null>(null);
  const [editMember, setEditMember] = useState<TeamMember | null>(null);
  const [selectedTeamId, setSelectedTeamId] = useState('');
  const [teamForm, setTeamForm] = useState({ name: '', description: '' });
  const [memberForm, setMemberForm] = useState({ name: '', email: '', role: 'member', permissions: [] as string[] });
  const [formLoading, setFormLoading] = useState(false);

  const fetchTeams = useCallback(async () => {
    try {
      const r = await fetch('/api/admin/teams');
      const d = await r.json();
      if (d.success) setTeams(d.teams?.length ? d.teams : getDefaultTeams());
      else setTeams(getDefaultTeams());
    } catch { setTeams(getDefaultTeams()); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { fetchTeams(); }, [fetchTeams]);

  const getDefaultTeams = (): Team[] => [
    { id: '1', name: 'Content Team', description: 'Manages listings and MCQ content', members: [
      { id: 'm1', name: 'Rahim Uddin', email: 'rahim@needyfy.com', role: 'lead', permissions: ['manage_listings', 'manage_mcq', 'view_analytics'], teamId: '1' },
      { id: 'm2', name: 'Fatima Akter', email: 'fatima@needyfy.com', role: 'member', permissions: ['manage_listings', 'manage_mcq'], teamId: '1' },
    ]},
    { id: '2', name: 'Support Team', description: 'Handles orders and community', members: [
      { id: 'm3', name: 'Karim Hossain', email: 'karim@needyfy.com', role: 'lead', permissions: ['manage_orders', 'manage_community', 'send_notifications', 'view_analytics'], teamId: '2' },
    ]},
    { id: '3', name: 'Operations', description: 'Platform operations and settings', members: [] },
  ];

  const handleTeamSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setFormLoading(true);
    try {
      const method = editTeam ? 'PATCH' : 'POST';
      const body = editTeam ? { id: editTeam.id, ...teamForm } : teamForm;
      await fetch('/api/admin/teams', { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
    } catch { }
    setShowTeamDialog(false); setEditTeam(null); setTeamForm({ name: '', description: '' }); fetchTeams(); setFormLoading(false);
  };

  const handleDeleteTeam = async (id: string) => {
    try { await fetch('/api/admin/teams', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) }); } catch { }
    fetchTeams();
  };

  const handleMemberSubmit = async (e: React.FormEvent) => {
    e.preventDefault(); setFormLoading(true);
    try {
      await fetch('/api/admin/teams/members', {
        method: editMember ? 'PATCH' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editMember ? { id: editMember.id, ...memberForm, teamId: selectedTeamId } : { ...memberForm, teamId: selectedTeamId })
      });
    } catch { }
    setShowMemberDialog(false); setEditMember(null); setMemberForm({ name: '', email: '', role: 'member', permissions: [] }); fetchTeams(); setFormLoading(false);
  };

  const handleDeleteMember = async (memberId: string) => {
    try { await fetch('/api/admin/teams/members', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: memberId }) }); } catch { }
    fetchTeams();
  };

  const handlePermSubmit = async () => {
    setFormLoading(true);
    try {
      await fetch('/api/admin/teams/permissions', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ memberId: editMember?.id, permissions: memberForm.permissions })
      });
    } catch { }
    setShowPermDialog(false); setEditMember(null); fetchTeams(); setFormLoading(false);
  };

  const togglePerm = (key: string) => {
    setMemberForm(prev => ({
      ...prev,
      permissions: prev.permissions.includes(key) ? prev.permissions.filter(p => p !== key) : [...prev.permissions, key]
    }));
  };

  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Team Management</h3>
          <p className="text-sm text-muted-foreground">Create teams, add members, and assign limited tasks &amp; permissions</p>
        </div>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={() => { setEditTeam(null); setTeamForm({ name: '', description: '' }); setShowTeamDialog(true); }}>
          <Plus className="h-4 w-4" />Create Team
        </Button>
      </div>

      <div className="grid gap-6">
        {teams.map((team) => (
          <Card key={team.id} className="border-0 shadow-sm">
            <CardContent className="p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-orange-500 to-amber-500 text-white shadow-sm">
                    <UsersRound className="h-5 w-5" />
                  </div>
                  <div>
                    <h4 className="font-semibold">{team.name}</h4>
                    <p className="text-xs text-muted-foreground">{team.description}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="text-[10px]">{team.members?.length || 0} members</Badge>
                  <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => { setEditTeam(team); setTeamForm({ name: team.name, description: team.description }); setShowTeamDialog(true); }}><Pencil className="h-3.5 w-3.5" /></Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader><AlertDialogTitle>Delete Team</AlertDialogTitle><AlertDialogDescription>Delete &quot;{team.name}&quot; and remove all members?</AlertDialogDescription></AlertDialogHeader>
                      <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => handleDeleteTeam(team.id)} className="bg-destructive text-destructive-foreground">Delete</AlertDialogAction></AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </div>

              <div className="space-y-2">
                {team.members?.map((member) => (
                  <div key={member.id} className="flex items-center justify-between rounded-xl bg-slate-50 p-3 dark:bg-slate-800/50">
                    <div className="flex items-center gap-3">
                      <div className="flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-orange-400 to-amber-400 text-xs font-bold text-white">{member.name.charAt(0)}</div>
                      <div>
                        <div className="flex items-center gap-2">
                          <p className="text-sm font-medium">{member.name}</p>
                          <Badge className={`text-[9px] border-0 ${member.role === 'lead' ? 'bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400' : 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300'}`}>{member.role === 'lead' ? 'Lead' : 'Member'}</Badge>
                        </div>
                        <p className="text-xs text-muted-foreground">{member.email}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="hidden sm:flex flex-wrap gap-1">
                        {member.permissions.slice(0, 3).map((p) => (
                          <span key={p} className="inline-flex items-center gap-1 rounded-md bg-white px-1.5 py-0.5 text-[10px] text-slate-600 dark:bg-slate-700 dark:text-slate-300 shadow-sm">
                            <Key className="h-2.5 w-2.5" />{TASK_PERMISSIONS.find(tp => tp.key === p)?.label || p}
                          </span>
                        ))}
                        {member.permissions.length > 3 && <span className="text-[10px] text-muted-foreground">+{member.permissions.length - 3}</span>}
                      </div>
                      <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => { setEditMember(member); setMemberForm({ name: member.name, email: member.email, role: member.role, permissions: member.permissions }); setShowPermDialog(true); }} title="Edit permissions"><Shield className="h-3.5 w-3.5 text-orange-500" /></Button>
                      <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => { setEditMember(member); setMemberForm({ name: member.name, email: member.email, role: member.role, permissions: member.permissions }); setSelectedTeamId(team.id); setShowMemberDialog(true); }} title="Edit member"><Pencil className="h-3.5 w-3.5" /></Button>
                      <AlertDialog>
                        <AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-7 w-7"><Trash2 className="h-3 w-3 text-destructive" /></Button></AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader><AlertDialogTitle>Remove Member</AlertDialogTitle><AlertDialogDescription>Remove {member.name} from {team.name}?</AlertDialogDescription></AlertDialogHeader>
                          <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => handleDeleteMember(member.id)} className="bg-destructive text-destructive-foreground">Remove</AlertDialogAction></AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </div>
                ))}
                {(!team.members || team.members.length === 0) && (
                  <div className="py-6 text-center text-sm text-muted-foreground">No members yet</div>
                )}
              </div>

              <Button variant="outline" size="sm" className="mt-3 gap-2 text-xs" onClick={() => { setSelectedTeamId(team.id); setEditMember(null); setMemberForm({ name: '', email: '', role: 'member', permissions: [] }); setShowMemberDialog(true); }}>
                <UserPlus className="h-3.5 w-3.5" />Add Member
              </Button>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Team Dialog */}
      <Dialog open={showTeamDialog} onOpenChange={(o) => { setShowTeamDialog(o); if (!o) setEditTeam(null); }}>
        <DialogContent className="sm:max-w-[420px]">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><UsersRound className="h-5 w-5 text-orange-500" />{editTeam ? 'Edit Team' : 'Create Team'}</DialogTitle><DialogDescription>{editTeam ? 'Update team details' : 'Create a new team for your organization'}</DialogDescription></DialogHeader>
          <form onSubmit={handleTeamSubmit} className="space-y-3 pt-2">
            <div className="space-y-1.5"><Label className="text-xs font-medium">Team Name</Label><Input value={teamForm.name} onChange={(e) => setTeamForm({ ...teamForm, name: e.target.value })} required /></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Description</Label><Input value={teamForm.description} onChange={(e) => setTeamForm({ ...teamForm, description: e.target.value })} /></div>
            <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={formLoading}>{formLoading ? 'Saving...' : editTeam ? 'Update Team' : 'Create Team'}</Button>
          </form>
        </DialogContent>
      </Dialog>

      {/* Member Dialog */}
      <Dialog open={showMemberDialog} onOpenChange={(o) => { setShowMemberDialog(o); if (!o) setEditMember(null); }}>
        <DialogContent className="sm:max-w-[480px]">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><UserPlus className="h-5 w-5 text-orange-500" />{editMember ? 'Edit Member' : 'Add Team Member'}</DialogTitle><DialogDescription>Assign role and limited task permissions</DialogDescription></DialogHeader>
          <form onSubmit={handleMemberSubmit} className="space-y-3 pt-2">
            <div className="space-y-1.5"><Label className="text-xs font-medium">Name</Label><Input value={memberForm.name} onChange={(e) => setMemberForm({ ...memberForm, name: e.target.value })} required /></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Email</Label><div className="relative"><Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /><Input type="email" value={memberForm.email} onChange={(e) => setMemberForm({ ...memberForm, email: e.target.value })} className="pl-9" required /></div></div>
            <div className="space-y-1.5">
              <Label className="text-xs font-medium">Role</Label>
              <select value={memberForm.role} onChange={(e) => setMemberForm({ ...memberForm, role: e.target.value })} className="w-full rounded-lg border bg-background px-3 py-2 text-sm">
                <option value="lead">Team Lead</option><option value="member">Member</option>
              </select>
            </div>
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label className="text-xs font-semibold">Task Permissions</Label>
                <div className="flex gap-2">
                  <Button type="button" variant="outline" size="sm" className="text-xs h-6" onClick={() => setMemberForm({ ...memberForm, permissions: TASK_PERMISSIONS.map(p => p.key) })}><CheckCircle className="mr-1 h-3 w-3" />All</Button>
                  <Button type="button" variant="outline" size="sm" className="text-xs h-6" onClick={() => setMemberForm({ ...memberForm, permissions: [] })}><XCircle className="mr-1 h-3 w-3" />None</Button>
                </div>
              </div>
              <div className="grid grid-cols-1 gap-1.5 max-h-48 overflow-y-auto">
                {TASK_PERMISSIONS.map((perm) => (
                  <label key={perm.key} className={`flex items-center gap-2 rounded-lg border px-3 py-2 cursor-pointer transition-all ${memberForm.permissions.includes(perm.key) ? 'border-orange-500 bg-orange-50 dark:bg-orange-950/20' : 'hover:border-slate-300'}`}>
                    <input type="checkbox" checked={memberForm.permissions.includes(perm.key)} onChange={() => togglePerm(perm.key)} className="sr-only" />
                    <div className={`h-4 w-4 rounded border flex items-center justify-center shrink-0 ${memberForm.permissions.includes(perm.key) ? 'bg-orange-500 border-orange-500' : 'border-slate-300'}`}>
                      {memberForm.permissions.includes(perm.key) && <CheckCircle className="h-3 w-3 text-white" />}
                    </div>
                    <div><p className="text-xs font-medium">{perm.label}</p><p className="text-[10px] text-muted-foreground">{perm.desc}</p></div>
                  </label>
                ))}
              </div>
            </div>
            <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={formLoading}>{formLoading ? 'Saving...' : editMember ? 'Update Member' : 'Add Member'}</Button>
          </form>
        </DialogContent>
      </Dialog>

      {/* Permission Dialog */}
      <Dialog open={showPermDialog} onOpenChange={(o) => { setShowPermDialog(o); if (!o) setEditMember(null); }}>
        <DialogContent className="sm:max-w-[480px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2"><Shield className="h-5 w-5 text-orange-500" />Edit Permissions</DialogTitle>
            <DialogDescription>{editMember && `Update permissions for ${editMember.name}`}</DialogDescription>
          </DialogHeader>
          <div className="space-y-3 pt-2">
            <div className="flex items-center justify-between">
              <Label className="text-xs font-semibold">Task Permissions</Label>
              <div className="flex gap-2">
                <Button type="button" variant="outline" size="sm" className="text-xs h-6" onClick={() => setMemberForm({ ...memberForm, permissions: TASK_PERMISSIONS.map(p => p.key) })}><CheckCircle className="mr-1 h-3 w-3" />All</Button>
                <Button type="button" variant="outline" size="sm" className="text-xs h-6" onClick={() => setMemberForm({ ...memberForm, permissions: [] })}><XCircle className="mr-1 h-3 w-3" />None</Button>
              </div>
            </div>
            <div className="grid grid-cols-1 gap-1.5 max-h-64 overflow-y-auto">
              {TASK_PERMISSIONS.map((perm) => (
                <label key={perm.key} className={`flex items-center gap-2 rounded-lg border px-3 py-2 cursor-pointer transition-all ${memberForm.permissions.includes(perm.key) ? 'border-orange-500 bg-orange-50 dark:bg-orange-950/20' : 'hover:border-slate-300'}`}>
                  <input type="checkbox" checked={memberForm.permissions.includes(perm.key)} onChange={() => togglePerm(perm.key)} className="sr-only" />
                  <div className={`h-4 w-4 rounded border flex items-center justify-center shrink-0 ${memberForm.permissions.includes(perm.key) ? 'bg-orange-500 border-orange-500' : 'border-slate-300'}`}>
                    {memberForm.permissions.includes(perm.key) && <CheckCircle className="h-3 w-3 text-white" />}
                  </div>
                  <div><p className="text-xs font-medium">{perm.label}</p><p className="text-[10px] text-muted-foreground">{perm.desc}</p></div>
                </label>
              ))}
            </div>
            <Button className={`w-full ${ORANGE_BTN} font-semibold`} onClick={handlePermSubmit} disabled={formLoading}>{formLoading ? 'Saving...' : 'Save Permissions'}</Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
