'use client';

import { useState, useEffect } from 'react';
import DataTable from '@/components/admin/DataTable';
import DetailModal from '@/components/admin/DetailModal';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, Users } from 'lucide-react';
import Link from 'next/link';

const CLASSIFICATION_LABELS: Record<number, string> = {
  5: 'Block Hour',
  9: 'Canceled',
  202: 'Co-Managed',
  16: 'Gold (Legacy)',
  206: 'IT Complete w/ Gold Security',
  207: 'IT Core / Silver Security',
  203: 'IT Foundation / Bronze Security',
  205: 'IT Premier / Platinum Security',
  14: 'Jeopardy Company',
  201: 'Partner',
  15: 'Platinum (Legacy)',
  13: 'Residential (no-pay)',
  17: 'Silver (Legacy)',
  12: 'T&M',
  7: 'Target',
  200: 'Tools Only',
  18: 'Bronze (Legacy)',
};

function classificationLabel(val: any): string {
  if (val === null || val === undefined || val === '') return '—';
  const num = parseInt(String(val), 10);
  return CLASSIFICATION_LABELS[num] ?? String(val);
}

export default function CompaniesBrowserPage() {
  const [companies, setCompanies] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(50);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedCompany, setSelectedCompany] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const fetchCompanies = async (currentPage: number, search?: string, sortBy?: string, sortOrder?: string) => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString(),
      });
      
      if (search) params.append('search', search);
      if (sortBy) params.append('sort', sortBy);
      if (sortOrder) params.append('order', sortOrder);

      const response = await fetch(`/api/data/companies?${params}`);
      const result = await response.json();
      
      setCompanies(result.data || []);
      setTotalCount(result.pagination?.total || 0);
    } catch (error) {
      console.error('Failed to fetch companies:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCompanies(page);
  }, [page]);

  const handleRowClick = (company: any) => {
    setSelectedCompany(company);
    setModalOpen(true);
  };

  const columns = [
    {
      key: 'id',
      label: 'ID',
      sortable: true,
    },
    {
      key: 'company_name',
      label: 'Company Name',
      sortable: true,
      render: (value: string) => (
        <div className="font-medium">{value}</div>
      ),
    },
    {
      key: 'company_number',
      label: 'Company #',
      sortable: true,
    },
    {
      key: 'phone',
      label: 'Phone',
    },
    {
      key: 'city',
      label: 'City',
      sortable: true,
    },
    {
      key: 'state',
      label: 'State',
    },
    {
      key: 'classification',
      label: 'Classification',
      sortable: true,
      render: (value: any) => classificationLabel(value),
    },
    {
      key: 'is_active',
      label: 'Active',
      render: (value: boolean) => (
        <Badge variant={value ? 'default' : 'secondary'}>
          {value ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
    {
      key: 'is_deleted',
      label: 'Deleted',
      render: (value: boolean) => (
        <Badge variant={value ? 'destructive' : 'secondary'}>
          {value ? 'Yes' : 'No'}
        </Badge>
      ),
    },
  ];

  const detailFields = [
    { key: 'id', label: 'ID' },
    { key: 'company_name', label: 'Company Name' },
    { key: 'company_number', label: 'Company Number' },
    { key: 'is_active', label: 'Active' },
    { key: 'phone', label: 'Phone' },
    { key: 'alternate_phone1', label: 'Alternate Phone 1' },
    { key: 'alternate_phone2', label: 'Alternate Phone 2' },
    { key: 'fax', label: 'Fax' },
    { key: 'web_site_url', label: 'Website' },
    { key: 'address1', label: 'Address 1' },
    { key: 'address2', label: 'Address 2' },
    { key: 'city', label: 'City' },
    { key: 'state', label: 'State' },
    { key: 'postal_code', label: 'Postal Code' },
    { key: 'country', label: 'Country' },
    { key: 'classification', label: 'Classification', render: (v: any) => classificationLabel(v) },
    { key: 'company_type', label: 'Company Type' },
    { key: 'company_category_id', label: 'Company Category ID' },
    { key: 'owner_resource_id', label: 'Owner Resource ID' },
    { key: 'territory_id', label: 'Territory ID' },
    { key: 'market_segment_id', label: 'Market Segment ID' },
    { key: 'parent_company_id', label: 'Parent Company ID' },
    { key: 'create_date', label: 'Created (AT)' },
    { key: 'synced_at', label: 'Synced At' },
    { key: 'is_deleted', label: 'Is Deleted' },
  ];

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center gap-3">
        <Link href="/admin/data-browser">
          <Button variant="ghost" size="sm">
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back
          </Button>
        </Link>
        <Users className="w-6 h-6" />
        <div>
          <h1 className="text-2xl font-bold">Companies Browser</h1>
          <p className="text-sm text-muted-foreground">Browse and inspect company data</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Companies</CardTitle>
          <CardDescription>
            {totalCount} total companies in database
          </CardDescription>
        </CardHeader>
        <CardContent>
          <DataTable
            columns={columns}
            data={companies}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchCompanies(page, undefined, column, direction)}
            onSearch={(query) => fetchCompanies(1, query)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
            exportable
            exportFilename="companies"
          />
        </CardContent>
      </Card>

      <DetailModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        title={`Company: ${selectedCompany?.company_name || selectedCompany?.id}`}
        data={selectedCompany}
        fields={detailFields}
      />
    </div>
  );
}
