import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { partnerApi } from '../../api/partner';
import { useAuth } from '../../contexts/AuthContext';
import { AppLayout } from '../../components/layout/AppLayout';
import { PageLoader } from '../../components/ui/LoadingSpinner';
import { Building2, Search, ExternalLink, ArrowUpRight, ArrowDownRight, Plus } from 'lucide-react';
import type { Organization } from '../../types';

export function OrganizationsPage() {
  const [search, setSearch] = useState('');
  const [selectedOrg, setSelectedOrg] = useState<string | null>(null);
  const { hasCompanyPermission } = useAuth();

  const { data, isLoading } = useQuery({
    queryKey: ['organizations'],
    queryFn: () => partnerApi.getOrganizations(),
  });

  const organizations = data?.items ?? [];
  const canCreateOrg = hasCompanyPermission('create_org');

  const filtered = organizations.filter((org) =>
    org.name.toLowerCase().includes(search.toLowerCase()) ||
    org.location.toLowerCase().includes(search.toLowerCase())
  );

  if (isLoading) {
    return (
      <AppLayout title="Organizations">
        <PageLoader />
      </AppLayout>
    );
  }

  return (
    <AppLayout title="Organizations">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold text-surface-900 truncate">Organizations</h1>
          <p className="mt-1 text-sm text-surface-500">
            {organizations.length} organization{organizations.length !== 1 ? 's' : ''} in your portfolio
          </p>
        </div>
        <div className="flex items-center gap-3">
          {canCreateOrg && (
            <button
              className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 transition-colors min-h-[44px]"
            >
              <Plus className="h-4 w-4" />
              New Organization
            </button>
          )}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-surface-400" />
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search organizations..."
              className="w-full rounded-lg border border-surface-300 py-2.5 pl-9 pr-4 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100 sm:w-72"
            />
          </div>
        </div>
      </div>

      {/* Organizations Grid */}
      {filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-surface-200 bg-white py-16">
          <Building2 className="h-12 w-12 text-surface-300" />
          <p className="mt-4 text-sm font-medium text-surface-700">
            {search ? 'No organizations match your search' : 'No organizations yet'}
          </p>
          <p className="mt-1 text-sm text-surface-500">
            {search ? 'Try a different search term' : 'Add your first organization to get started'}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
          {filtered.map((org) => (
            <div
              key={org.id}
              onClick={() => setSelectedOrg(selectedOrg === org.id ? null : org.id)}
              className={`cursor-pointer rounded-xl border bg-white p-5 transition-all hover:shadow-md ${
                selectedOrg === org.id ? 'border-brand-300 ring-2 ring-brand-100' : 'border-surface-200'
              }`}
            >
              {/* Org Header */}
              <div className="mb-3 flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-100 text-brand-600">
                    <Building2 className="h-5 w-5" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-surface-900">{org.name}</h3>
                    <p className="text-xs text-surface-500">{org.location || 'No location'}</p>
                  </div>
                </div>
                <span
                  className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                    org.status === 'active'
                      ? 'bg-success/10 text-success'
                      : 'bg-surface-200 text-surface-600'
                  }`}
                >
                  {org.status}
                </span>
              </div>

              {/* Stats Row */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <p className="text-xs text-surface-500">Revenue</p>
                  <p className="text-sm font-semibold text-surface-900">
                    ${org.annual_revenue.toLocaleString()}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-surface-500">Growth</p>
                  <div className="flex items-center gap-0.5">
                    {org.revenue_growth >= 0 ? (
                      <ArrowUpRight className="h-3 w-3 text-success" />
                    ) : (
                      <ArrowDownRight className="h-3 w-3 text-error" />
                    )}
                    <p
                      className={`text-sm font-semibold ${
                        org.revenue_growth >= 0 ? 'text-success' : 'text-error'
                      }`}
                    >
                      {Math.abs(org.revenue_growth).toFixed(1)}%
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-xs text-surface-500">Projects</p>
                  <p className="text-sm font-semibold text-surface-900">{org.active_projects}</p>
                </div>
              </div>

              {/* Expanded Details */}
              {selectedOrg === org.id && (
                <div className="mt-4 animate-fade-in rounded-lg bg-surface-50 p-4">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                    <div>
                      <span className="text-surface-500">Tier:</span>{' '}
                      <span className="font-medium capitalize">{org.tier}</span>
                    </div>
                    <div>
                      <span className="text-surface-500">Industry:</span>{' '}
                      <span className="font-medium">{org.industry}</span>
                    </div>
                    <div>
                      <span className="text-surface-500">Target:</span>{' '}
                      <span className="font-medium">${org.target_revenue.toLocaleString()}</span>
                    </div>
                    <div>
                      <span className="text-surface-500">Commission:</span>{' '}
                      <span className="font-medium">{(org.commission_rate * 100).toFixed(0)}%</span>
                    </div>
                  </div>
                  {org.website && (
                    <a
                      href={org.website}
                      target="_blank"
                      rel="noopener noreferrer"
                      onClick={(e) => e.stopPropagation()}
                      className="mt-3 inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-sm font-medium text-brand-600 hover:text-brand-700 hover:bg-brand-50 transition-colors min-h-[44px]"
                    >
                      Visit Website <ExternalLink className="h-3 w-3" />
                    </a>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </AppLayout>
  );
}
