import { useState } from 'react';
import { PageLayout } from './organisms/PageLayout';
import { PageHeader } from './organisms/PageHeader';
import { Users, Plus, Edit, Trash2, Shield, UserCheck, UserX } from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from './ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from './ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from './ui/alert-dialog';
import { Card, CardContent } from './ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
import { Badge } from './ui/badge';
import { useData, type User, type UserRole } from './contexts/DataContext';
import { toast } from 'sonner@2.0.3';

const roleLabels: Record<UserRole, string> = {
  CEO: '대표이사',
  ProductionManager: '생산관리자',
  Worker: '생산작업자',
  SystemAdmin: '시스템관리자',
  Sales: '영업사원'
};

const roleColors: Record<UserRole, string> = {
  CEO: 'bg-purple-100 text-purple-700',
  ProductionManager: 'bg-blue-100 text-blue-700',
  Worker: 'bg-green-100 text-green-700',
  SystemAdmin: 'bg-orange-100 text-orange-700',
  Sales: 'bg-pink-100 text-pink-700'
};

export function UserManagement() {
  const { users, addUser, updateUser, deleteUser } = useData();
  
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterRole, setFilterRole] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  
  const [formData, setFormData] = useState<Partial<User>>({
    username: '',
    email: '',
    password: '',
    name: '',
    role: 'Worker',
    companyName: '',
    position: '',
    phone: '',
    isActive: true
  });

  const handleOpenDialog = (user?: User) => {
    if (user) {
      setEditingUser(user);
      setFormData(user);
    } else {
      setEditingUser(null);
      setFormData({
        username: '',
        email: '',
        password: '',
        name: '',
        role: 'Worker',
        companyName: '',
        position: '',
        phone: '',
        isActive: true
      });
    }
    setIsDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setIsDialogOpen(false);
    setEditingUser(null);
    setFormData({
      username: '',
      email: '',
      password: '',
      name: '',
      role: 'Worker',
      companyName: '',
      position: '',
      phone: '',
      isActive: true
    });
  };

  const handleSubmit = () => {
    if (!formData.username || !formData.email || !formData.name || !formData.role) {
      toast.error('필수 항목을 입력해주세요');
      return;
    }

    if (!editingUser && !formData.password) {
      toast.error('비밀번호를 입력해주세요');
      return;
    }

    // 중복 체크 (신규 등록 또는 수정 시 다른 사용자와 중복)
    const duplicateUsername = users.find(
      u => u.username === formData.username && (!editingUser || u.id !== editingUser.id)
    );
    if (duplicateUsername) {
      toast.error('이미 사용 중인 사용자명입니다');
      return;
    }

    const duplicateEmail = users.find(
      u => u.email === formData.email && (!editingUser || u.id !== editingUser.id)
    );
    if (duplicateEmail) {
      toast.error('이미 사용 중인 이메일입니다');
      return;
    }

    if (editingUser) {
      updateUser(editingUser.id, formData);
      toast.success('사용자가 수정되었습니다');
    } else {
      const newUser: User = {
        id: `USER-${Date.now()}`,
        username: formData.username!,
        email: formData.email!,
        password: formData.password!,
        name: formData.name!,
        role: formData.role as UserRole,
        companyName: formData.companyName!,
        position: formData.position,
        phone: formData.phone,
        isActive: formData.isActive ?? true,
        createdAt: new Date().toISOString().split('T')[0]
      };
      addUser(newUser);
      toast.success('사용자가 추가되었습니다');
    }

    handleCloseDialog();
  };

  const handleDelete = () => {
    if (deleteTarget) {
      deleteUser(deleteTarget.id);
      toast.success('사용자가 삭제되었습니다');
      setDeleteTarget(null);
    }
  };

  const handleToggleStatus = (user: User) => {
    updateUser(user.id, { isActive: !user.isActive });
    toast.success(user.isActive ? '사용자가 비활성화되었습니다' : '사용자가 활성화되었습니다');
  };

  // 필터링된 사용자 목록
  const filteredUsers = users.filter(user => {
    const matchesSearch = 
      user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.companyName.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesRole = filterRole === 'all' || user.role === filterRole;
    const matchesStatus = filterStatus === 'all' || 
      (filterStatus === 'active' && user.isActive) ||
      (filterStatus === 'inactive' && !user.isActive);

    return matchesSearch && matchesRole && matchesStatus;
  });

  // 통계
  const stats = {
    total: users.length,
    active: users.filter(u => u.isActive).length,
    inactive: users.filter(u => !u.isActive).length,
    byRole: {
      CEO: users.filter(u => u.role === 'CEO').length,
      ProductionManager: users.filter(u => u.role === 'ProductionManager').length,
      Worker: users.filter(u => u.role === 'Worker').length,
      SystemAdmin: users.filter(u => u.role === 'SystemAdmin').length,
      Sales: users.filter(u => u.role === 'Sales').length
    }
  };

  return (
    <PageLayout
      devMetadata={{
        componentName: '사용자관리',
        pagePath: '/components/UserManagement.tsx',
        description: '시스템 사용자를 등록하고 역할별 권한을 관리하는 시스템',
        
        apis: [
          {
            endpoint: '/api/v1/users',
            method: 'GET',
            description: '사용자 목록 조회',
            queryParams: [
              { name: 'role', type: 'string', required: false, description: '역할 필터 (CEO, ProductionManager, Worker, SystemAdmin, Sales)' },
              { name: 'isActive', type: 'boolean', required: false, description: '활성 상태 필터' },
              { name: 'search', type: 'string', required: false, description: '검색어 (이름, 이메일, 아이디)' },
            ],
            responseBody: {
              success: true,
              data: [{ id: 'USER-001', username: 'admin', name: '김대표', role: 'CEO', isActive: true }]
            }
          },
          {
            endpoint: '/api/v1/users',
            method: 'POST',
            description: '사용자 등록',
            requestBody: {
              username: 'admin',
              email: 'admin@company.com',
              password: 'hashed_password',
              name: '김대표',
              role: 'CEO',
            },
            responseBody: {
              success: true,
              data: { id: 'USER-001' }
            }
          },
        ],
        
        dataStructures: [
          {
            name: 'User',
            type: 'interface',
            fields: [
              { name: 'id', type: 'string', required: true, description: '고유 ID' },
              { name: 'username', type: 'string', required: true, description: '사용자 아이디' },
              { name: 'email', type: 'string', required: true, description: '이메일' },
              { name: 'password', type: 'string', required: true, description: '비밀번호 (해시)' },
              { name: 'name', type: 'string', required: true, description: '이름' },
              { name: 'role', type: 'UserRole', required: true, description: '역할' },
              { name: 'isActive', type: 'boolean', required: true, description: '활성 상태' },
            ],
          },
        ],
        
        dbSchema: [
          {
            tableName: 'users',
            columns: [
              { name: 'id', type: 'VARCHAR(50)', nullable: false, key: 'PK', description: '고유 식별자' },
              { name: 'username', type: 'VARCHAR(50)', nullable: false, description: '사용자 아이디 (UNIQUE)' },
              { name: 'email', type: 'VARCHAR(200)', nullable: false, description: '이메일 (UNIQUE)' },
              { name: 'password_hash', type: 'VARCHAR(255)', nullable: false, description: '비밀번호 해시' },
              { name: 'name', type: 'VARCHAR(100)', nullable: false, description: '이름' },
              { name: 'role', type: 'ENUM', nullable: false, description: 'CEO, ProductionManager, Worker, SystemAdmin, Sales' },
              { name: 'is_active', type: 'BOOLEAN', nullable: false, description: '활성 상태' },
            ],
            indexes: ['idx_username', 'idx_email', 'idx_role'],
          },
        ],
        
        businessLogic: [
          {
            name: '사용자 등록',
            description: '신규 사용자를 시스템에 등록',
            steps: [
              '사용자 정보 입력 (아이디, 이메일, 비밀번호, 이름)',
              '역할 선택 (대표이사/생산관리자/생산작업자/시스템관리자/영업사원)',
              '중복 검사 (아이디, 이메일)',
              '비밀번호 해시 처리 (bcrypt)',
              'DataContext에 저장',
              '성공 토스트 메시지',
            ]
          },
        ],
      }}
    >
      <PageHeader
        title="사용자 관리"
        description="시스템 사용자를 등록하고 권한을 관리합니다"
        icon={Users}
      />

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">전체 사용자</p>
                <h3 className="text-2xl font-bold mt-1">{stats.total}</h3>
              </div>
              <Users className="w-10 h-10 text-blue-600 opacity-20" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">활성 사용자</p>
                <h3 className="text-2xl font-bold mt-1 text-green-600">{stats.active}</h3>
              </div>
              <UserCheck className="w-10 h-10 text-green-600 opacity-20" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">비활성 사용자</p>
                <h3 className="text-2xl font-bold mt-1 text-gray-600">{stats.inactive}</h3>
              </div>
              <UserX className="w-10 h-10 text-gray-600 opacity-20" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">시스템 관리자</p>
                <h3 className="text-2xl font-bold mt-1 text-orange-600">{stats.byRole.SystemAdmin}</h3>
              </div>
              <Shield className="w-10 h-10 text-orange-600 opacity-20" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 검색 및 필터 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-col md:flex-row gap-4 items-end">
            <div className="flex-1">
              <Label htmlFor="search">검색</Label>
              <Input
                id="search"
                placeholder="이름, 사용자명, 이메일, 회사명으로 검색..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="mt-2"
              />
            </div>

            <div className="w-full md:w-48">
              <Label htmlFor="filterRole">역할</Label>
              <Select value={filterRole} onValueChange={setFilterRole}>
                <SelectTrigger id="filterRole" className="mt-2">
                  <SelectValue placeholder="역할 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체</SelectItem>
                  <SelectItem value="CEO">대표이사</SelectItem>
                  <SelectItem value="ProductionManager">생산관리자</SelectItem>
                  <SelectItem value="Worker">생산작업자</SelectItem>
                  <SelectItem value="SystemAdmin">시스템관리자</SelectItem>
                  <SelectItem value="Sales">영업사원</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="w-full md:w-48">
              <Label htmlFor="filterStatus">상태</Label>
              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger id="filterStatus" className="mt-2">
                  <SelectValue placeholder="상태 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체</SelectItem>
                  <SelectItem value="active">활성</SelectItem>
                  <SelectItem value="inactive">비활성</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Button onClick={() => handleOpenDialog()} className="gap-2">
              <Plus className="w-4 h-4" />
              사용자 추가
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 사용자 목록 */}
      <Card>
        <CardContent className="pt-6">
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>사용자명</TableHead>
                  <TableHead>이름</TableHead>
                  <TableHead>이메일</TableHead>
                  <TableHead>회사명</TableHead>
                  <TableHead>직책</TableHead>
                  <TableHead>역할</TableHead>
                  <TableHead>상태</TableHead>
                  <TableHead>가입일</TableHead>
                  <TableHead className="text-right">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredUsers.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center text-gray-500 py-8">
                      사용자가 없습니다
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredUsers.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell className="font-medium">{user.username}</TableCell>
                      <TableCell>{user.name}</TableCell>
                      <TableCell className="text-gray-600">{user.email}</TableCell>
                      <TableCell>{user.companyName}</TableCell>
                      <TableCell className="text-gray-600">{user.position || '-'}</TableCell>
                      <TableCell>
                        <Badge className={roleColors[user.role]}>
                          {roleLabels[user.role]}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={user.isActive ? 'default' : 'secondary'}>
                          {user.isActive ? '활성' : '비활성'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-gray-600">{user.createdAt}</TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleToggleStatus(user)}
                            title={user.isActive ? '비활성화' : '활성화'}
                          >
                            {user.isActive ? <UserX className="w-4 h-4" /> : <UserCheck className="w-4 h-4" />}
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleOpenDialog(user)}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setDeleteTarget({ id: user.id, name: user.name })}
                          >
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 추가/수정 Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingUser ? '사용자 수정' : '사용자 추가'}</DialogTitle>
          </DialogHeader>

          <div className="grid grid-cols-2 gap-4 py-4">
            <div>
              <Label htmlFor="username">사용자명 (로그인 ID) *</Label>
              <Input
                id="username"
                value={formData.username}
                onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                placeholder="예: manager"
                disabled={!!editingUser}
              />
            </div>

            <div>
              <Label htmlFor="name">이름 *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="예: 홍길동"
              />
            </div>

            <div>
              <Label htmlFor="email">이메일 *</Label>
              <Input
                id="email"
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                placeholder="example@company.com"
              />
            </div>

            <div>
              <Label htmlFor="password">비밀번호 {!editingUser && '*'}</Label>
              <Input
                id="password"
                type="password"
                value={formData.password}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                placeholder={editingUser ? '변경하려면 입력' : '비밀번호'}
              />
            </div>

            <div>
              <Label htmlFor="role">역할 *</Label>
              <Select value={formData.role} onValueChange={(value) => setFormData({ ...formData, role: value as UserRole })}>
                <SelectTrigger id="role">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="CEO">대표이사</SelectItem>
                  <SelectItem value="ProductionManager">생산관리자</SelectItem>
                  <SelectItem value="Worker">생산작업자</SelectItem>
                  <SelectItem value="SystemAdmin">시스템관리자</SelectItem>
                  <SelectItem value="Sales">영업사원</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="companyName">회사명 *</Label>
              <Input
                id="companyName"
                value={formData.companyName}
                onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
                placeholder="예: 삼성전자"
              />
            </div>

            <div>
              <Label htmlFor="position">직책</Label>
              <Input
                id="position"
                value={formData.position}
                onChange={(e) => setFormData({ ...formData, position: e.target.value })}
                placeholder="예: 생산팀장"
              />
            </div>

            <div>
              <Label htmlFor="phone">연락처</Label>
              <Input
                id="phone"
                value={formData.phone}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                placeholder="010-0000-0000"
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={handleCloseDialog}>
              취소
            </Button>
            <Button onClick={handleSubmit}>
              {editingUser ? '수정' : '추가'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 Dialog */}
      <AlertDialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>사용자 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              정말로 "{deleteTarget?.name}" 사용자를 삭제하시겠습니까?
              <br />
              <span className="text-red-600 font-semibold">이 작업은 되돌릴 수 없습니다.</span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}
