"use client";

import { useState, useEffect } from "react";
import { Search, ChevronDown, ChevronUp, ExternalLink, FileText, User, Users, Calendar, Settings, ListChecks, Save, ShieldCheck, ShieldOff } from "lucide-react";

export default function AdminDashboard() {
  const [reports, setReports] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [tab, setTab] = useState<"REPORTS" | "USERS" | "SETTINGS">("REPORTS");
  const [folderId, setFolderId] = useState("");
  const [saving, setSaving] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [usersLoading, setUsersLoading] = useState(false);
  const [togglingId, setTogglingId] = useState<string | null>(null);

  useEffect(() => {
    fetchReports();
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      const res = await fetch("/api/admin/settings");
      const data = await res.json();
      if (data.GOOGLE_DRIVE_FOLDER_ID) {
        setFolderId(data.GOOGLE_DRIVE_FOLDER_ID);
      }
    } catch (error) {
      console.error("Failed to fetch settings");
    }
  };

  const saveSetting = async (key: string, value: string) => {
    setSaving(true);
    try {
      await fetch("/api/admin/settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ key, value }),
      });
      alert("Setting saved successfully!");
    } catch (error) {
      alert("Failed to save setting");
    } finally {
      setSaving(false);
    }
  };

  const fetchUsers = async () => {
    setUsersLoading(true);
    try {
      const res = await fetch("/api/admin/users");
      const data = await res.json();
      setUsers(data);
    } catch (error) {
      console.error("Failed to fetch users");
    } finally {
      setUsersLoading(false);
    }
  };

  const toggleRole = async (userId: string, currentRole: string) => {
    setTogglingId(userId);
    const newRole = currentRole === "ADMIN" ? "EMPLOYEE" : "ADMIN";
    try {
      const res = await fetch("/api/admin/users", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId, role: newRole }),
      });
      const data = await res.json();
      if (data.error) {
        alert(data.error);
      } else {
        setUsers(users.map(u => u.id === userId ? { ...u, role: newRole } : u));
      }
    } catch (error) {
      alert("Failed to update role");
    } finally {
      setTogglingId(null);
    }
  };

  const fetchReports = async () => {
    try {
      const res = await fetch("/api/reports");
      const data = await res.json();
      setReports(data);
    } catch (error) {
      console.error("Failed to fetch reports");
    } finally {
      setLoading(false);
    }
  };

  const filteredReports = reports.filter(r => 
    r.user?.name?.toLowerCase().includes(search.toLowerCase()) ||
    r.managerName?.toLowerCase().includes(search.toLowerCase())
  );

  if (loading) return <div className="text-center py-20 animate-pulse">Loading reports...</div>;

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-4">
            <button 
                onClick={() => setTab("REPORTS")}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
                    tab === "REPORTS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
                }`}
            >
                <ListChecks size={18} /> Reports
            </button>
            <button
                onClick={() => { setTab("USERS"); if (!users.length) fetchUsers(); }}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
                    tab === "USERS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
                }`}
            >
                <Users size={18} /> Users
            </button>
            <button
                onClick={() => setTab("SETTINGS")}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
                    tab === "SETTINGS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
                }`}
            >
                <Settings size={18} /> Settings
            </button>
        </div>
        
        {tab === "REPORTS" && (
            <div className="relative max-w-sm w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-dim" size={18} />
              <input 
                type="text" 
                placeholder="Search by employee or manager..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="glass-input w-full pl-10 pr-4 py-2 rounded-lg text-sm"
              />
            </div>
        )}
      </div>

      {tab === "REPORTS" ? (
        <div className="grid gap-4">
        {filteredReports.map((report) => (
          <div key={report.id} className="glass-card overflow-hidden transition-all duration-300">
            <div 
              className="p-4 flex items-center justify-between cursor-pointer hover:bg-white/5"
              onClick={() => setExpandedId(expandedId === report.id ? null : report.id)}
            >
              <div className="flex items-center gap-4">
                <div className="h-10 w-10 rounded-full bg-accent-primary/20 flex items-center justify-center text-accent-primary">
                    <User size={20} />
                </div>
                <div>
                  <h3 className="font-semibold">{report.user?.name || "Unknown User"}</h3>
                  <p className="text-xs text-text-dim flex items-center gap-1">
                    <Calendar size={12} /> {new Date(report.date).toLocaleDateString()} • Manager: {report.managerName}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-4">
                <span className={`text-[10px] uppercase tracking-wider px-2 py-1 rounded-full font-bold ${
                  report.status === 'SUBMITTED' ? 'bg-green-500/20 text-green-400' : 'bg-yellow-500/20 text-yellow-400'
                }`}>
                  {report.status}
                </span>
                {expandedId === report.id ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
              </div>
            </div>

            {expandedId === report.id && (
              <div className="p-6 border-t border-white/10 bg-black/20 space-y-6 animate-fade-in">
                <div className="grid md:grid-cols-2 gap-8">
                  <div className="space-y-3">
                    <h4 className="text-xs font-bold uppercase text-accent-primary tracking-widest">Planned Tasks</h4>
                    {report.tasks.filter((t: any) => t.type === 'PLANNED').map((task: any) => (
                      <div key={task.id} className="text-sm border-l-2 border-accent-primary/30 pl-3 py-1">
                        <p className="font-medium">{task.description}</p>
                        <p className="text-xs text-text-dim">Est: {task.timeEstimate} • {task.notes}</p>
                      </div>
                    ))}
                  </div>
                  <div className="space-y-3">
                    <h4 className="text-xs font-bold uppercase text-accent-secondary tracking-widest">Completed Tasks</h4>
                    {report.tasks.filter((t: any) => t.type === 'COMPLETED').map((task: any) => (
                      <div key={task.id} className="text-sm border-l-2 border-accent-secondary/30 pl-3 py-1">
                        <p className="font-medium">{task.description}</p>
                        <div className="flex items-center justify-between">
                            <span className="text-[10px] text-text-dim italic">{task.status}</span>
                            {task.link && (
                                <a href={task.link} target="_blank" className="text-accent-secondary hover:underline flex items-center gap-1 text-[10px]">
                                    <ExternalLink size={10} /> View Work
                                </a>
                            )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        ))}
        {filteredReports.length === 0 && <p className="text-center py-10 text-text-dim">No reports found matching your criteria.</p>}
        </div>
      ) : tab === "USERS" ? (
        <div className="space-y-4 animate-fade-in">
          <div>
            <h3 className="text-lg font-semibold flex items-center gap-2">
              <Users size={20} className="text-accent-primary" /> Employee List
            </h3>
            <p className="text-sm text-text-dim">Manage admin privileges for your team.</p>
          </div>

          {usersLoading ? (
            <div className="text-center py-10 animate-pulse text-text-dim">Loading users...</div>
          ) : (
            <div className="grid gap-3">
              {users.map((user) => {
                const lastReport = user.reports?.[0];
                return (
                  <div key={user.id} className="glass-card p-4 flex items-center justify-between gap-4">
                    <div className="flex items-center gap-4 min-w-0">
                      {user.image ? (
                        <img src={user.image} alt={user.name} className="h-10 w-10 rounded-full flex-shrink-0" />
                      ) : (
                        <div className="h-10 w-10 rounded-full bg-accent-primary/20 flex items-center justify-center text-accent-primary flex-shrink-0">
                          <User size={20} />
                        </div>
                      )}
                      <div className="min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <p className="font-semibold truncate">{user.name || "Unnamed"}</p>
                          <span className={`text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full font-bold flex-shrink-0 ${
                            user.role === "ADMIN"
                              ? "bg-accent-primary/20 text-accent-primary"
                              : "bg-white/10 text-text-dim"
                          }`}>
                            {user.role}
                          </span>
                        </div>
                        <p className="text-xs text-text-dim truncate">{user.email}</p>
                        {lastReport && (
                          <p className="text-[10px] text-text-dim mt-0.5">
                            Last report: {new Date(lastReport.date).toLocaleDateString()} •{" "}
                            <span className={lastReport.status === "SUBMITTED" ? "text-green-400" : "text-yellow-400"}>
                              {lastReport.status}
                            </span>
                          </p>
                        )}
                      </div>
                    </div>

                    <button
                      onClick={() => toggleRole(user.id, user.role)}
                      disabled={togglingId === user.id}
                      className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors flex-shrink-0 disabled:opacity-50 ${
                        user.role === "ADMIN"
                          ? "bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20"
                          : "bg-accent-primary/10 hover:bg-accent-primary/20 text-accent-primary border border-accent-primary/20"
                      }`}
                      title={user.role === "ADMIN" ? "Remove admin privileges" : "Grant admin privileges"}
                    >
                      {togglingId === user.id ? (
                        "..."
                      ) : user.role === "ADMIN" ? (
                        <><ShieldOff size={16} /> Remove Admin</>
                      ) : (
                        <><ShieldCheck size={16} /> Make Admin</>
                      )}
                    </button>
                  </div>
                );
              })}
              {users.length === 0 && (
                <p className="text-center py-10 text-text-dim">No users found.</p>
              )}
            </div>
          )}
        </div>
      ) : (
        <div className="glass-card p-8 space-y-8 animate-fade-in">
            <div className="space-y-4">
              <div>
                <h3 className="text-lg font-semibold flex items-center gap-2">
                    <FileText size={20} className="text-accent-primary" /> Google Drive Configuration
                </h3>
                <p className="text-sm text-text-dim">Designate a specific folder where all exported reports will be saved.</p>
              </div>

              <div className="space-y-2">
                <label className="text-xs font-bold uppercase text-text-dim tracking-wider">Google Drive Folder ID</label>
                <input 
                    type="text" 
                    value={folderId}
                    onChange={(e) => setFolderId(e.target.value)}
                    placeholder="Enter Folder ID (from URL)"
                    className="glass-input w-full px-4 py-3 rounded-xl text-sm"
                />
                <p className="text-[10px] text-text-dim italic">
                    Example ID: `1abc12345xyz_...` (Found in the URL of your Google Drive folder)
                </p>
              </div>

              <button 
                onClick={() => saveSetting('GOOGLE_DRIVE_FOLDER_ID', folderId)}
                disabled={saving}
                className="btn-primary flex items-center gap-2 px-8"
              >
                <Save size={18} /> {saving ? "Saving..." : "Save Settings"}
              </button>
            </div>
        </div>
      )}
    </div>
  );
}
