import { useState, useEffect } from "react";
import { Plus, Trash2, Pencil, RefreshCcw } from "lucide-react";
import MaterialTable from "@material-table/core";
import { getAllRoles, Role as ApiRole } from "../api/roles";
import { createUser, getAllUsers, CreateUserInput, User as ApiUser } from "../api/users";

interface User {
  id: string;
  name: string;
  email: string;
  roleId: string;
  roleName: string;
  status: "ACTIVE" | "INACTIVE";
  createdAt: string;
}

interface UserForm {
  firstName: string;
  lastName: string;
  email: string;
  password?: string;
  roleId: string;
  status: "ACTIVE" | "INACTIVE";
  createdAt: string;
}

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [activeUser, setActiveUser] = useState<User | null>(null);
  const [search, setSearch] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [roles, setRoles] = useState<ApiRole[]>([]);
  const [loadingRoles, setLoadingRoles] = useState(true);
  const [loadingUsers, setLoadingUsers] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const emptyUser: UserForm = { firstName: "", lastName: "", email: "", roleId: "", password: "", status: "ACTIVE", createdAt: new Date().toISOString().slice(0,10) };
  const [form, setForm] = useState<UserForm>(emptyUser);

  // Fetch roles and users from API on component mount
  useEffect(() => {
    const fetchRoles = async () => {
      try {
        setLoadingRoles(true);
        const rolesData = await getAllRoles();
        console.log('Roles fetched:', rolesData);
        setRoles(rolesData);
      } catch (error) {
        console.error('Failed to fetch roles:', error);
      } finally {
        setLoadingRoles(false);
      }
    };

    const fetchUsers = async () => {
      try {
        setLoadingUsers(true);
        const usersResponse = await getAllUsers();
        console.log('Users API response:', usersResponse);
        
        // Map API users to UI format
        const mappedUsers: User[] = usersResponse.data.map((apiUser: ApiUser) => ({
          id: apiUser.id,
          name: `${apiUser.first_name} ${apiUser.last_name}`,
          email: apiUser.email,
          roleId: apiUser.role_id,
          roleName: apiUser.role?.name || '',
          status: apiUser.is_active ? "ACTIVE" : "INACTIVE",
          createdAt: new Date(apiUser.created_at).toISOString().slice(0, 10)
        }));
        
        console.log('Mapped users:', mappedUsers);
        setUsers(mappedUsers);
      } catch (error) {
        console.error('Failed to fetch users:', error);
        // Keep empty array on error
        setUsers([]);
      } finally {
        setLoadingUsers(false);
      }
    };

    fetchRoles();
    fetchUsers();
  }, []);

  const handleSave = async () => {
    setError(null);
    
    // Validation
    if (!form.firstName || !form.lastName || !form.email || !form.roleId) {
      setError("Please fill in all required fields");
      return;
    }

    if (!editingId && !form.password) {
      setError("Password is required for new users");
      return;
    }

    if (form.password && form.password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }

    try {
      setSaving(true);
      
      if (editingId) {
        // TODO: Implement update user
        const roleName = roles.find(r => r.id === form.roleId)?.name || "";
        const fullName = `${form.firstName} ${form.lastName}`;
        setUsers(prev => prev.map(u => u.id === editingId ? { 
          id: editingId, 
          name: fullName,
          email: form.email,
          roleId: form.roleId,
          roleName, 
          status: form.status,
          createdAt: form.createdAt
        } : u));
      } else {
        // Create new user
        const roleIdNum = parseInt(form.roleId, 10);
        
        if (isNaN(roleIdNum)) {
          setError("Please select a valid role");
          return;
        }

        const createData: CreateUserInput = {
          email: form.email,
          password: form.password!,
          first_name: form.firstName,
          last_name: form.lastName,
          role_id: roleIdNum,
          is_active: form.status === "ACTIVE",
        };

        const newUser = await createUser(createData);
        const roleName = roles.find(r => r.id === form.roleId)?.name || "";
        
        // Add the new user to the list
        const apiUser: ApiUser = newUser;
        setUsers(prev => [...prev, {
          id: apiUser.id,
          name: `${apiUser.first_name} ${apiUser.last_name}`,
          email: apiUser.email,
          roleId: apiUser.role_id,
          roleName: roleName,
          status: apiUser.is_active ? "ACTIVE" : "INACTIVE",
          createdAt: new Date(apiUser.created_at).toISOString().slice(0, 10)
        }]);
      }
      
      setShowModal(false);
      setEditingId(null);
      setForm(emptyUser);
    } catch (err) {
      console.error('Failed to save user:', err);
      setError(err instanceof Error ? err.message : 'Failed to save user');
    } finally {
      setSaving(false);
    }
  };

  const handleRefresh = async () => {
    try {
      setLoadingUsers(true);
      const usersResponse = await getAllUsers();
      const mappedUsers: User[] = usersResponse.data.map((apiUser: ApiUser) => ({
        id: apiUser.id,
        name: `${apiUser.first_name} ${apiUser.last_name}`,
        email: apiUser.email,
        roleId: apiUser.role_id,
        roleName: apiUser.role?.name || '',
        status: apiUser.is_active ? "ACTIVE" : "INACTIVE",
        createdAt: new Date(apiUser.created_at).toISOString().slice(0, 10)
      }));
      setUsers(mappedUsers);
    } catch (error) {
      console.error('Failed to refresh users:', error);
    } finally {
      setLoadingUsers(false);
    }
  };

  const handleDelete = () => {
    if (!activeUser) return;
    setUsers(prev => prev.filter(u => u.id !== activeUser.id));
    setActiveUser(null);
  };

  const filtered = users.filter(u => u.name.toLowerCase().includes(search.toLowerCase()) || u.email.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="flex gap-6 p-6 w-full bg-gray-100">
      {/* LEFT INFO SIDEBAR */}
      <div className="w-72 bg-white rounded-xl shadow p-4">
        <h3 className="text-xs font-semibold text-gray-500 mb-3">Project Information</h3>
        <p className="text-sm text-gray-700">Usuarios disponibles y sus roles.</p>
        <select value={form.roleId} onChange={e => setForm({...form, roleId: e.target.value})} className="w-full border px-3 py-2 rounded mt-2" disabled={loadingRoles}>
          <option value="">{loadingRoles ? "Loading roles..." : "Select Role"}</option>
          {roles.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
        </select>
      </div>

      {/* MAIN */}
      <div className="flex-1 flex flex-col gap-6">
        {/* HEADER */}
        <div className="rounded-xl shadow p-6 text-white flex justify-between items-center"
             style={{ background: "linear-gradient(135deg, #4c5f9e, #2a355d, #566bb8)" }}>
          <div>
            <h1 className="text-2xl font-bold">User Management</h1>
            <p className="text-sm text-blue-100">Usuarios registrados</p>
          </div>
          <div className="flex gap-3">
            <button onClick={() => { setForm(emptyUser); setEditingId(null); setShowModal(true); }} className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg"><Plus size={16} /> Add</button>
            <button onClick={() => { 
              if(!activeUser) return; 
              const [firstName = "", lastName = ""] = activeUser.name.split(" ");
              setEditingId(activeUser.id); 
              setForm({
                firstName,
                lastName,
                email: activeUser.email,
                roleId: activeUser.roleId,
                status: activeUser.status,
                createdAt: activeUser.createdAt,
                password: ""
              }); 
              setShowModal(true); 
            }} disabled={!activeUser} className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"><Pencil size={16}/> Edit</button>
            <button onClick={handleDelete} disabled={!activeUser} className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg disabled:opacity-60"><Trash2 size={16}/> Delete</button>
            <button onClick={handleRefresh} className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg" disabled={loadingUsers}><RefreshCcw size={16}/> Refresh</button>
          </div>
        </div>

        {/* SEARCH */}
        <input className="bg-white rounded-lg shadow px-4 py-2 text-sm" placeholder="Search user..." value={search} onChange={e => setSearch(e.target.value)} />

        {/* TABLE */}
        {loadingUsers ? (
          <div className="bg-white rounded-xl shadow p-8 text-center">
            <p className="text-gray-500">Loading users...</p>
          </div>
        ) : (
          <MaterialTable
            title="Users"
            columns={[
              { title: "Name", field: "name" },
              { title: "Email", field: "email" },
              { title: "Role", field: "roleName" },
              { title: "Status", field: "status", render: rowData => <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${rowData.status === "ACTIVE" ? "text-blue-600 border-blue-600" : "text-red-600 border-red-600"}`}>{rowData.status}</span> },
              { title: "Created", field: "createdAt", type: "date" }
            ]}
            data={filtered}
            onRowClick={(_, rowData) => setActiveUser(rowData as User)}
            options={{ actionsColumnIndex: -1, search: false, paging: true, sorting: true, rowStyle: rowData => ({ backgroundColor: activeUser?.id === (rowData as User).id ? "#EEF2FF" : "#FFFFFF" }) }}
          />
        )}
      </div>

      {/* MODAL */}
      {showModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center">
          <div className="bg-white rounded-xl p-6 w-96 space-y-3">
            <h2 className="text-lg font-semibold">{editingId ? "Edit User" : "Add User"}</h2>
            
            {error && (
              <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-2 rounded text-sm">
                {error}
              </div>
            )}
            
            <input 
              className="w-full border px-3 py-2 rounded" 
              placeholder="First Name *" 
              value={form.firstName} 
              onChange={e => setForm({...form, firstName: e.target.value})}
              disabled={saving}
            />
            
            <input 
              className="w-full border px-3 py-2 rounded" 
              placeholder="Last Name *" 
              value={form.lastName} 
              onChange={e => setForm({...form, lastName: e.target.value})}
              disabled={saving}
            />
            
            <input 
              className="w-full border px-3 py-2 rounded" 
              type="email"
              placeholder="Email *" 
              value={form.email} 
              onChange={e => setForm({...form, email: e.target.value})}
              disabled={saving}
            />
            
            {!editingId && (
              <input 
                className="w-full border px-3 py-2 rounded" 
                type="password"
                placeholder="Password * (min 8 characters)" 
                value={form.password || ""} 
                onChange={e => setForm({...form, password: e.target.value})}
                disabled={saving}
              />
            )}
            
            <select 
              value={form.roleId} 
              onChange={e => setForm({...form, roleId: e.target.value})} 
              className="w-full border px-3 py-2 rounded" 
              disabled={loadingRoles || saving}
            >
              <option value="">Select Role *</option>
              {roles.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
            
            <button 
              onClick={() => setForm({...form, status: form.status === "ACTIVE" ? "INACTIVE" : "ACTIVE"})} 
              className="w-full border rounded px-3 py-2"
              disabled={saving}
            >
              Status: {form.status}
            </button>
            
            <div className="flex justify-end gap-2 pt-3">
              <button 
                onClick={() => { setShowModal(false); setError(null); }} 
                className="px-4 py-2"
                disabled={saving}
              >
                Cancel
              </button>
              <button 
                onClick={handleSave} 
                className="bg-[#4c5f9e] text-white px-4 py-2 rounded disabled:opacity-50"
                disabled={saving || loadingRoles}
              >
                {saving ? "Saving..." : "Save"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
