'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import { toast } from 'react-toastify';

interface Client { id: number; name: string; }
interface Cfg { id: number; client: number; client_name: string; author_urn: string; oauth_client_id: string; is_active: boolean; has_token: boolean; }

export default function CompanyLinkedInPage() {
  const { user } = useAuth();
  const [clients, setClients] = useState<Client[]>([]);
  const [cfgs, setCfgs] = useState<Record<number, Cfg>>({});
  const [loading, setLoading] = useState(true);

  const [editClient, setEditClient] = useState<Client | null>(null);
  const [form, setForm] = useState({ author_urn: '', access_token: '', oauth_client_id: '', oauth_client_secret: '', is_active: true });
  const [saving, setSaving] = useState(false);

  const unwrap = (r: any) => { const d = r?.data ?? r; return Array.isArray(d) ? d : (d?.results ?? []); };

  const load = async () => {
    setLoading(true);
    try {
      const cl = unwrap(await api.get('/clients/?page_size=500')) as Client[];
      setClients(cl);
      const cf = unwrap(await api.get('/clients/linkedin-configs/')) as Cfg[];
      const map: Record<number, Cfg> = {};
      cf.forEach((c) => { map[c.client] = c; });
      setCfgs(map);
    } catch (err) {
      console.error('Failed to load LinkedIn configs:', err);
    } finally { setLoading(false); }
  };
  useEffect(() => { if (!user) return; load(); /* eslint-disable-next-line */ }, [user]);

  const openEdit = (client: Client) => {
    const c = cfgs[client.id];
    setEditClient(client);
    setForm({ author_urn: c?.author_urn || '', access_token: '', oauth_client_id: c?.oauth_client_id || '', oauth_client_secret: '', is_active: c?.is_active ?? true });
  };

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editClient) return;
    setSaving(true);
    try {
      const existing = cfgs[editClient.id];
      const payload: any = { client: editClient.id, author_urn: form.author_urn, oauth_client_id: form.oauth_client_id, is_active: form.is_active };
      if (form.access_token.trim()) payload.access_token = form.access_token.trim();
      if (form.oauth_client_secret.trim()) payload.oauth_client_secret = form.oauth_client_secret.trim();
      if (existing) await api.patch(`/clients/linkedin-configs/${existing.id}/`, payload);
      else await api.post('/clients/linkedin-configs/', payload);
      toast.success('LinkedIn config saved.');
      setEditClient(null);
      await load();
    } catch (err: any) {
      toast.error(err?.data?.message || err?.data?.errors?.author_urn?.[0] || 'Could not save.');
    } finally { setSaving(false); }
  };

  if (!user) return null;

  return (
    <>
      <main className="flex-1 p-8 overflow-y-auto w-full max-w-5xl mx-auto space-y-5">
          <div>
            <h2 className="text-lg font-black text-slate-800 dark:text-white">Company LinkedIn Configuration</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400">Each company can have its own LinkedIn access token & organization URN. When a JD is posted to LinkedIn, its company&apos;s credentials are used (falling back to the global token if none set).</p>
          </div>

          {loading ? (
            <p className="text-slate-400 text-sm">Loading…</p>
          ) : (
            <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-sm">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-100 dark:border-slate-800 text-left">
                    {['Company', 'LinkedIn URN', 'Token', 'Status', ''].map((h) => (
                      <th key={h} className="py-3 px-4 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50 dark:divide-slate-800">
                  {clients.length === 0 && <tr><td colSpan={5} className="py-8 text-center text-slate-400">No companies. Add clients first.</td></tr>}
                  {clients.map((cl) => {
                    const c = cfgs[cl.id];
                    return (
                      <tr key={cl.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40">
                        <td className="py-3 px-4 font-bold text-slate-800 dark:text-white">{cl.name}</td>
                        <td className="py-3 px-4 text-slate-600 dark:text-slate-400 text-xs">{c?.author_urn || <span className="text-slate-400">—</span>}</td>
                        <td className="py-3 px-4">
                          {c?.has_token
                            ? <span className="text-[10px] font-bold px-2 py-0.5 bg-emerald-50 text-emerald-700 border border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300">Set</span>
                            : <span className="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-slate-500 border border-slate-200 dark:bg-slate-800">Not set</span>}
                        </td>
                        <td className="py-3 px-4">
                          {c ? (c.is_active
                            ? <span className="text-[10px] font-bold text-emerald-600">Active</span>
                            : <span className="text-[10px] font-bold text-slate-400">Inactive</span>) : <span className="text-slate-300 text-xs">—</span>}
                        </td>
                        <td className="py-3 px-4 text-right">
                          <button onClick={() => openEdit(cl)} className="text-xs font-bold text-[#405189] border border-[#405189]/30 px-3 py-1.5 hover:bg-[#405189]/5 transition">
                            {c ? 'Edit' : 'Configure'}
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
      </main>

      {editClient && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <form onSubmit={save} className="w-full max-w-md bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 shadow-xl p-6">
            <div className="flex items-center justify-between border-b border-slate-100 dark:border-slate-800 pb-3 mb-4">
              <h3 className="text-base font-black text-slate-800 dark:text-white">LinkedIn — {editClient.name}</h3>
              <button type="button" onClick={() => setEditClient(null)} className="text-slate-400 hover:text-slate-600">✕</button>
            </div>
            {['author_urn', 'access_token', 'oauth_client_id', 'oauth_client_secret'].map((k) => (
              <div key={k} className="mb-3">
                <label className="block text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-1">
                  {k === 'author_urn' ? 'Organization / Author URN' : k === 'access_token' ? 'Access Token' : k === 'oauth_client_id' ? 'App Client ID (optional)' : 'App Client Secret (optional)'}
                </label>
                <input
                  value={(form as any)[k]} onChange={(e) => setForm({ ...form, [k]: e.target.value })}
                  placeholder={k === 'author_urn' ? 'urn:li:organization:12345' : (k.includes('token') || k.includes('secret')) && cfgs[editClient.id] ? '•••• (leave blank to keep)' : ''}
                  className="w-full px-3 py-2.5 text-sm border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 focus:outline-none focus:border-[#405189]" />
              </div>
            ))}
            <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200 cursor-pointer mt-1">
              <input type="checkbox" checked={form.is_active} onChange={(e) => setForm({ ...form, is_active: e.target.checked })} className="w-4 h-4 accent-[#405189]" />
              Active (use for this company&apos;s JD postings)
            </label>
            <div className="flex justify-end gap-2 mt-5">
              <button type="button" onClick={() => setEditClient(null)} className="px-4 py-2 border border-slate-200 dark:border-slate-700 text-sm font-semibold">Cancel</button>
              <button type="submit" disabled={saving} className="px-6 py-2 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition disabled:opacity-50">{saving ? 'Saving…' : 'Save'}</button>
            </div>
          </form>
        </div>
      )}
    </>
  );
}
