'use client';

import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Trash2, Plus, Edit2 } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { isValidEmail } from '@/lib/utils';

interface User {
  id: number;
  email: string;
  name: string | null;
  isAdmin: boolean;
  hasWriteAccess: boolean;
  isActive?: boolean;
  createdAt: string;
  updatedAt: string;
}

type UserStatusFilter = 'all' | 'active' | 'inactive';

export function ManageUsersContent() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<UserStatusFilter>('active');
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);

  // Form state
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    name: '',
    hasWriteAccess: false,
    isAdmin: false,
    isActive: true,
  });

  // Fetch users
  const fetchUsers = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      console.log('[ManageUsers] Fetching users with filter:', statusFilter);
      const url = statusFilter === 'all' 
        ? '/api/users?status=all'
        : statusFilter === 'inactive'
        ? '/api/users?status=inactive'
        : '/api/users?status=active';
      
      console.log('[ManageUsers] Fetching from URL:', url);
      const response = await fetch(url, {
        credentials: 'include', // Ensure cookies are sent
      });
      
      console.log('[ManageUsers] Response status:', response.status, response.statusText);
      
      let data;
      const contentType = response.headers.get('content-type');
      console.log('[ManageUsers] Content-Type:', contentType);
      
      try {
        const text = await response.text();
        console.log('[ManageUsers] Response text:', text);
        data = text ? JSON.parse(text) : {};
      } catch (parseError) {
        console.error('[ManageUsers] Failed to parse response:', parseError);
        throw new Error(`Server error (${response.status}): Invalid JSON response`);
      }
      
      console.log('[ManageUsers] Parsed data:', data);
      
      if (!response.ok) {
        const errorMsg = data?.error || data?.details || data?.message || `HTTP ${response.status}: ${response.statusText}`;
        console.error('[ManageUsers] API Error:', { 
          status: response.status, 
          statusText: response.statusText,
          data 
        });
        throw new Error(errorMsg);
      }
      
      if (!data.users) {
        console.warn('[ManageUsers] Response missing users array:', data);
        setUsers([]);
      } else {
        console.log('[ManageUsers] Successfully loaded', data.users.length, 'users');
        setUsers(data.users);
      }
    } catch (err: any) {
      console.error('[ManageUsers] Error fetching users:', err);
      setError(err.message || 'Failed to load users');
    } finally {
      setLoading(false);
    }
  }, [statusFilter]);

  // Debug: Log when statusFilter changes
  useEffect(() => {
    console.log('[ManageUsers] statusFilter state changed to:', statusFilter);
  }, [statusFilter]);

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

  // Handle add user
  const handleAddUser = async () => {
    try {
      setError(null);
      
      // Client-side validation
      if (!formData.name || formData.name.trim().length === 0) {
        setError('Name is required');
        return;
      }
      
      if (!formData.email || !isValidEmail(formData.email)) {
        setError('Please enter a valid email address');
        return;
      }
      
      const response = await fetch('/api/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to create user');
      }

      setIsAddDialogOpen(false);
      setFormData({ email: '', password: '', name: '', hasWriteAccess: false, isAdmin: false, isActive: true });
      fetchUsers();
    } catch (err: any) {
      setError(err.message || 'Failed to create user');
    }
  };


  // Handle edit user
  const handleEditUser = async () => {
    if (!editingUser) return;

    try {
      setError(null);
      
      // Client-side validation
      if (!formData.name || formData.name.trim().length === 0) {
        setError('Name is required');
        return;
      }
      
      const updateData: any = {};
      if (formData.email !== editingUser.email) {
        updateData.email = formData.email;
      }
      if (formData.name !== editingUser.name) {
        updateData.name = formData.name;
      }
      if (formData.password) {
        updateData.password = formData.password;
      }
      if (formData.hasWriteAccess !== editingUser.hasWriteAccess) {
        updateData.hasWriteAccess = formData.hasWriteAccess;
      }
      if (formData.isAdmin !== editingUser.isAdmin) {
        updateData.isAdmin = formData.isAdmin;
      }
      // Treat undefined/null as true, so only check if explicitly false
      const currentIsActive = editingUser.isActive !== false;
      if (formData.isActive !== currentIsActive) {
        updateData.isActive = formData.isActive;
      }

      if (Object.keys(updateData).length === 0) {
        setIsEditDialogOpen(false);
        return;
      }

      const response = await fetch(`/api/users/${editingUser.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updateData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to update user');
      }

      setIsEditDialogOpen(false);
      setEditingUser(null);
      setFormData({ email: '', password: '', name: '', hasWriteAccess: false, isAdmin: false, isActive: true });
      fetchUsers();
    } catch (err: any) {
      setError(err.message || 'Failed to update user');
    }
  };

  // Handle delete user
  const handleDeleteUser = async () => {
    if (!userToDelete) return;

    try {
      setError(null);
      setSuccessMessage(null);
      const response = await fetch(`/api/users/${userToDelete.id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to delete user');
      }

      const data = await response.json();
      setDeleteConfirmOpen(false);
      setUserToDelete(null);
      
      // Check if user was deactivated instead of deleted
      if (data.deactivated) {
        setSuccessMessage(
          `User ${userToDelete.email} was deactivated (not deleted) because they have ${data.relatedRecords?.pendingLinkages || 0} pending linkages, ${data.relatedRecords?.photoFavorites || 0} favorites, and other related records.`
        );
      } else {
        setSuccessMessage(`User ${userToDelete.email} was deleted successfully.`);
      }
      
      // Clear success message after 5 seconds
      setTimeout(() => setSuccessMessage(null), 5000);
      
      fetchUsers();
    } catch (err: any) {
      setError(err.message || 'Failed to delete user');
    }
  };

  // Open edit dialog
  const openEditDialog = (user: User) => {
    setEditingUser(user);
    setFormData({
      email: user.email,
      password: '',
      name: user.name || '',
      hasWriteAccess: user.hasWriteAccess,
      isAdmin: user.isAdmin,
      isActive: user.isActive !== false, // Treat undefined/null as true
    });
    setIsEditDialogOpen(true);
  };

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="text-center">Loading users...</div>
      </div>
    );
  }

  return (
    <div className="container mx-auto max-w-7xl">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Manage Users</h1>
          <p className="text-muted-foreground mt-1">
            Manage user accounts and permissions
          </p>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <label htmlFor="status-filter" className="text-sm font-medium">
              User Status:
            </label>
            <Select 
              value={statusFilter} 
              onValueChange={(value) => {
                console.log('[ManageUsers] Filter changed to:', value);
                setStatusFilter(value as UserStatusFilter);
              }}
            >
              <SelectTrigger id="status-filter" className="w-[150px]">
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent className="z-[120]">
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="active">Active only</SelectItem>
                <SelectItem value="inactive">Inactive only</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Button onClick={() => setIsAddDialogOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Add User
          </Button>
        </div>
      </div>

      {error && (
        <div className="mb-4 rounded-md bg-red-50 p-4 text-red-800 dark:bg-red-900/20 dark:text-red-400">
          {error}
        </div>
      )}

      {successMessage && (
        <div className="mb-4 rounded-md bg-green-50 p-4 text-green-800 dark:bg-green-900/20 dark:text-green-400">
          {successMessage}
        </div>
      )}

      <div className="rounded-lg border bg-card">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b">
                <th className="px-4 py-3 text-left text-sm font-medium">Email</th>
                <th className="px-4 py-3 text-left text-sm font-medium">Name</th>
                <th className="px-4 py-3 text-left text-sm font-medium">Status</th>
                <th className="px-4 py-3 text-left text-sm font-medium">Role</th>
                <th className="px-4 py-3 text-left text-sm font-medium">Write Access</th>
                <th className="px-4 py-3 text-left text-sm font-medium">Created</th>
                <th className="px-4 py-3 text-right text-sm font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr key={user.id} className="border-b">
                  <td className="px-4 py-3">{user.email}</td>
                  <td className="px-4 py-3">{user.name || '-'}</td>
                  <td className="px-4 py-3">
                    {user.isActive === false ? (
                      <Badge variant="outline" className="border-red-300 text-red-700 dark:border-red-800 dark:text-red-400">Inactive</Badge>
                    ) : (
                      <Badge variant="outline" className="border-green-300 text-green-700 dark:border-green-800 dark:text-green-400">Active</Badge>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    {user.isAdmin ? (
                      <Badge variant="outline" className="border-blue-300 text-blue-700 dark:border-blue-800 dark:text-blue-400">Admin</Badge>
                    ) : (
                      <Badge variant="outline" className="border-gray-300 text-gray-700 dark:border-gray-600 dark:text-gray-400">User</Badge>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm">
                      {user.hasWriteAccess ? 'Yes' : 'No'}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm text-muted-foreground">
                    {new Date(user.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => openEditDialog(user)}
                      >
                        <Edit2 className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setUserToDelete(user);
                          setDeleteConfirmOpen(true);
                        }}
                        className="text-red-600 hover:text-red-700"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add User Dialog */}
      <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
        <DialogContent className="z-[110]" overlayClassName="z-[105]">
          <DialogHeader>
            <DialogTitle>Add New User</DialogTitle>
            <DialogDescription>
              Create a new user account. Write access can be granted later.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <label htmlFor="add-email" className="text-sm font-medium">
                Email <span className="text-red-500">*</span>
              </label>
              <Input
                id="add-email"
                type="email"
                value={formData.email}
                onChange={(e) =>
                  setFormData({ ...formData, email: e.target.value })
                }
                placeholder="user@example.com"
              />
            </div>
            <div className="grid gap-2">
              <label htmlFor="add-password" className="text-sm font-medium">
                Password <span className="text-red-500">*</span>
              </label>
              <Input
                id="add-password"
                type="password"
                value={formData.password}
                onChange={(e) =>
                  setFormData({ ...formData, password: e.target.value })
                }
                placeholder="Minimum 6 characters"
              />
            </div>
            <div className="grid gap-2">
              <label htmlFor="add-name" className="text-sm font-medium">
                Name <span className="text-red-500">*</span>
              </label>
              <Input
                id="add-name"
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                placeholder="Enter full name"
                required
              />
            </div>
            <div className="grid gap-2">
              <label htmlFor="add-role" className="text-sm font-medium">
                Role <span className="text-red-500">*</span>
              </label>
              <Select
                value={formData.isAdmin ? 'admin' : 'user'}
                onValueChange={(value) =>
                  setFormData({ 
                    ...formData, 
                    isAdmin: value === 'admin',
                    hasWriteAccess: value === 'admin' ? true : formData.hasWriteAccess
                  })
                }
              >
                <SelectTrigger id="add-role" className="w-full">
                  <SelectValue placeholder="Select role" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="user">User</SelectItem>
                  <SelectItem value="admin">Admin</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="add-write-access"
                checked={formData.hasWriteAccess}
                onCheckedChange={(checked) =>
                  setFormData({ ...formData, hasWriteAccess: !!checked })
                }
              />
              <label
                htmlFor="add-write-access"
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                Grant Write Access
              </label>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsAddDialogOpen(false);
                setFormData({ email: '', password: '', name: '', hasWriteAccess: false, isAdmin: false, isActive: true });
              }}
            >
              Cancel
            </Button>
            <Button onClick={handleAddUser}>Create User</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit User Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="z-[110]" overlayClassName="z-[105]">
          <DialogHeader>
            <DialogTitle>Edit User</DialogTitle>
            <DialogDescription>
              Update user information. Leave password blank to keep current password.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <label htmlFor="edit-email" className="text-sm font-medium">
                Email <span className="text-red-500">*</span>
              </label>
              <Input
                id="edit-email"
                type="email"
                value={formData.email}
                onChange={(e) =>
                  setFormData({ ...formData, email: e.target.value })
                }
                placeholder="user@example.com"
              />
            </div>
            <div className="grid gap-2">
              <label htmlFor="edit-password" className="text-sm font-medium">
                New Password <span className="text-gray-500 font-normal">(leave empty to keep current)</span>
              </label>
              <Input
                id="edit-password"
                type="password"
                value={formData.password}
                onChange={(e) =>
                  setFormData({ ...formData, password: e.target.value })
                }
                placeholder="Leave blank to keep current password"
              />
            </div>
            <div className="grid gap-2">
              <label htmlFor="edit-name" className="text-sm font-medium">
                Name <span className="text-red-500">*</span>
              </label>
              <Input
                id="edit-name"
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                placeholder="Enter full name"
                required
              />
            </div>
            <div className="grid gap-2">
              <label htmlFor="edit-role" className="text-sm font-medium">
                Role <span className="text-red-500">*</span>
              </label>
              <Select
                value={formData.isAdmin ? 'admin' : 'user'}
                onValueChange={(value) =>
                  setFormData({ 
                    ...formData, 
                    isAdmin: value === 'admin',
                    hasWriteAccess: value === 'admin' ? true : formData.hasWriteAccess
                  })
                }
              >
                <SelectTrigger id="edit-role" className="w-full">
                  <SelectValue placeholder="Select role" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="user">User</SelectItem>
                  <SelectItem value="admin">Admin</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="edit-write-access"
                checked={formData.hasWriteAccess}
                onCheckedChange={(checked) =>
                  setFormData({ ...formData, hasWriteAccess: !!checked })
                }
              />
              <label
                htmlFor="edit-write-access"
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                Grant Write Access
              </label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="edit-active"
                checked={formData.isActive}
                onCheckedChange={(checked) =>
                  setFormData({ ...formData, isActive: !!checked })
                }
              />
              <label
                htmlFor="edit-active"
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                Active
              </label>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsEditDialogOpen(false);
                setEditingUser(null);
                setFormData({ email: '', password: '', name: '', hasWriteAccess: false, isAdmin: false, isActive: true });
              }}
            >
              Cancel
            </Button>
            <Button onClick={handleEditUser}>Save Changes</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
        <DialogContent className="z-[110]" overlayClassName="z-[105]">
          <DialogHeader>
            <DialogTitle>Delete User</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete {userToDelete?.email}? This action
              cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setDeleteConfirmOpen(false);
                setUserToDelete(null);
              }}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeleteUser}
            >
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

