"use client";

import { useEffect, useState, useCallback } from "react";
import {
  RefreshCw,
  Building2,
  CheckCircle2,
  AlertCircle,
  Pencil,
  X,
  Save,
} from "lucide-react";

interface OrgRow {
  id: string;
  name: string;
  ownerId: string;
  industry: string | null;
  twilioWhatsappNumber: string | null;
  twilioAccountSidMasked: string | null;
  hasCredentials: boolean;
}

interface EditState {
  twilioAccountSid: string;
  twilioAuthToken: string;
  twilioWhatsappNumber: string;
}

export default function OrganizationsList() {
  const [orgs, setOrgs] = useState<OrgRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editState, setEditState] = useState<EditState>({
    twilioAccountSid: "",
    twilioAuthToken: "",
    twilioWhatsappNumber: "",
  });
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [search, setSearch] = useState("");

  const fetchOrgs = useCallback(async (showRefresh = false) => {
    if (showRefresh) setRefreshing(true);
    else setLoading(true);

    try {
      const res = await fetch("/api/staff/organizations");
      if (res.ok) {
        const data = await res.json();
        setOrgs(data.organizations ?? []);
      }
    } catch (err) {
      console.error("Failed to fetch organizations:", err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

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

  const handleEdit = (org: OrgRow) => {
    setEditingId(org.id);
    setEditState({
      twilioAccountSid: "",
      twilioAuthToken: "",
      twilioWhatsappNumber: org.twilioWhatsappNumber ?? "",
    });
    setSaveError(null);
  };

  const handleCancel = () => {
    setEditingId(null);
    setSaveError(null);
  };

  const handleSave = async (orgId: string) => {
    setSaving(true);
    setSaveError(null);

    try {
      const payload: Record<string, string> = { id: orgId };
      if (editState.twilioAccountSid.trim())
        payload.twilioAccountSid = editState.twilioAccountSid.trim();
      if (editState.twilioAuthToken.trim())
        payload.twilioAuthToken = editState.twilioAuthToken.trim();
      if (editState.twilioWhatsappNumber.trim())
        payload.twilioWhatsappNumber = editState.twilioWhatsappNumber.trim();

      const res = await fetch("/api/staff/organizations", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (res.ok) {
        setEditingId(null);
        await fetchOrgs(true);
      } else {
        const data = await res.json();
        setSaveError(data.error ?? "Failed to save");
      }
    } catch {
      setSaveError("Network error");
    } finally {
      setSaving(false);
    }
  };

  const filteredOrgs = orgs.filter(
    (o) =>
      !search ||
      o.name.toLowerCase().includes(search.toLowerCase()) ||
      (o.industry ?? "").toLowerCase().includes(search.toLowerCase()) ||
      (o.twilioWhatsappNumber ?? "").includes(search),
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading organizations...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats strip */}
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
          <p className="text-sm text-gray-500">Total Orgs</p>
          <p className="text-3xl font-bold text-brand-ink mt-1">
            {orgs.length}
          </p>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
          <p className="text-sm text-gray-500">WhatsApp Connected</p>
          <p className="text-3xl font-bold text-brand-green mt-1">
            {orgs.filter((o) => o.hasCredentials).length}
          </p>
        </div>
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
          <p className="text-sm text-gray-500">Pending Setup</p>
          <p className="text-3xl font-bold text-amber-500 mt-1">
            {orgs.filter((o) => !o.hasCredentials).length}
          </p>
        </div>
      </div>

      {/* Controls */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center justify-between gap-4 flex-wrap">
        <input
          type="text"
          placeholder="Search by name, industry, or number…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="flex-1 min-w-[200px] px-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green"
        />
        <button
          onClick={() => fetchOrgs(true)}
          disabled={refreshing}
          className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${refreshing ? "animate-spin" : ""}`} />
          Refresh
        </button>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center gap-2">
          <Building2 className="w-5 h-5 text-brand-green" />
          <h2 className="text-base font-semibold text-brand-ink">
            Organizations
          </h2>
          <span className="ml-auto text-sm text-gray-500">
            {filteredOrgs.length} of {orgs.length}
          </span>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide">
                <th className="px-6 py-3">Organization</th>
                <th className="px-6 py-3">Industry</th>
                <th className="px-6 py-3">WhatsApp Number</th>
                <th className="px-6 py-3">Account SID</th>
                <th className="px-6 py-3">Status</th>
                <th className="px-6 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {filteredOrgs.length === 0 && (
                <tr>
                  <td
                    colSpan={6}
                    className="px-6 py-12 text-center text-gray-400"
                  >
                    No organizations found
                  </td>
                </tr>
              )}

              {filteredOrgs.map((org) => (
                <>
                  <tr
                    key={org.id}
                    className="hover:bg-gray-50 transition-colors"
                  >
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-brand-green/10 rounded-lg flex items-center justify-center flex-shrink-0">
                          <Building2 className="w-4 h-4 text-brand-green" />
                        </div>
                        <div>
                          <p className="font-medium text-brand-ink">
                            {org.name}
                          </p>
                          <p className="text-xs text-gray-400 font-mono truncate max-w-[160px]">
                            {org.id}
                          </p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-gray-600">
                      {org.industry ?? (
                        <span className="text-gray-300">—</span>
                      )}
                    </td>
                    <td className="px-6 py-4 font-mono text-gray-600">
                      {org.twilioWhatsappNumber ?? (
                        <span className="text-gray-300">Not set</span>
                      )}
                    </td>
                    <td className="px-6 py-4 font-mono text-gray-400 text-xs">
                      {org.twilioAccountSidMasked ?? (
                        <span className="text-gray-300">Not set</span>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      {org.hasCredentials ? (
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-green-50 text-green-700 text-xs font-semibold rounded-full">
                          <CheckCircle2 className="w-3.5 h-3.5" />
                          Connected
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-amber-50 text-amber-700 text-xs font-semibold rounded-full">
                          <AlertCircle className="w-3.5 h-3.5" />
                          Pending
                        </span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <button
                        onClick={() => handleEdit(org)}
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition"
                      >
                        <Pencil className="w-3.5 h-3.5" />
                        Edit
                      </button>
                    </td>
                  </tr>

                  {/* Inline Edit Row */}
                  {editingId === org.id && (
                    <tr key={`${org.id}-edit`} className="bg-blue-50">
                      <td colSpan={6} className="px-6 py-5">
                        <div className="space-y-3">
                          <p className="text-sm font-semibold text-brand-ink mb-3">
                            Edit Twilio Credentials for{" "}
                            <span className="text-brand-green">{org.name}</span>
                          </p>

                          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                            <div>
                              <label className="block text-xs font-medium text-gray-600 mb-1">
                                Account SID
                              </label>
                              <input
                                type="text"
                                placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                                value={editState.twilioAccountSid}
                                onChange={(e) =>
                                  setEditState((s) => ({
                                    ...s,
                                    twilioAccountSid: e.target.value,
                                  }))
                                }
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green"
                              />
                            </div>
                            <div>
                              <label className="block text-xs font-medium text-gray-600 mb-1">
                                Auth Token
                              </label>
                              <input
                                type="password"
                                placeholder="Leave blank to keep current"
                                value={editState.twilioAuthToken}
                                onChange={(e) =>
                                  setEditState((s) => ({
                                    ...s,
                                    twilioAuthToken: e.target.value,
                                  }))
                                }
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green"
                              />
                            </div>
                            <div>
                              <label className="block text-xs font-medium text-gray-600 mb-1">
                                WhatsApp Number
                              </label>
                              <input
                                type="text"
                                placeholder="whatsapp:+1234567890"
                                value={editState.twilioWhatsappNumber}
                                onChange={(e) =>
                                  setEditState((s) => ({
                                    ...s,
                                    twilioWhatsappNumber: e.target.value,
                                  }))
                                }
                                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-green/30 focus:border-brand-green"
                              />
                            </div>
                          </div>

                          {saveError && (
                            <p className="text-sm text-red-600">{saveError}</p>
                          )}

                          <div className="flex items-center gap-2 pt-1">
                            <button
                              onClick={() => handleSave(org.id)}
                              disabled={saving}
                              className="inline-flex items-center gap-1.5 px-4 py-2 bg-brand-green text-white text-sm font-medium rounded-lg hover:bg-brand-greenHover disabled:opacity-50 transition"
                            >
                              <Save className="w-4 h-4" />
                              {saving ? "Saving…" : "Save"}
                            </button>
                            <button
                              onClick={handleCancel}
                              disabled={saving}
                              className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 transition"
                            >
                              <X className="w-4 h-4" />
                              Cancel
                            </button>
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
