'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';

export default function ContactsBrowserPage() {
  const [contacts, setContacts] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(50);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedContact, setSelectedContact] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const fetchContacts = 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/contacts?${params}`);
      const result = await response.json();
      
      setContacts(result.contacts || result.data || []);
      setTotalCount(result.pagination?.total || 0);
    } catch (error) {
      console.error('Failed to fetch contacts:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleRowClick = (contact: any) => {
    setSelectedContact(contact);
    setModalOpen(true);
  };

  const columns = [
    {
      key: 'id',
      label: 'ID',
      sortable: true,
    },
    {
      key: 'first_name',
      label: 'First Name',
      sortable: true,
    },
    {
      key: 'last_name',
      label: 'Last Name',
      sortable: true,
    },
    {
      key: 'email_address',
      label: 'Email',
      sortable: true,
      render: (value: string) => (
        <div className="max-w-xs truncate" title={value}>
          {value || '-'}
        </div>
      ),
    },
    {
      key: 'phone',
      label: 'Phone',
    },
    {
      key: 'company_id',
      label: 'Company ID',
      sortable: true,
    },
    {
      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_id', label: 'Company ID' },
    { key: 'first_name', label: 'First Name' },
    { key: 'last_name', label: 'Last Name' },
    { key: 'title', label: 'Title' },
    { key: 'email_address', label: 'Email' },
    { key: 'email_address2', label: 'Email 2' },
    { key: 'email_address3', label: 'Email 3' },
    { key: 'phone', label: 'Phone' },
    { key: 'extension', label: 'Extension' },
    { key: 'alternate_phone', label: 'Alternate Phone' },
    { key: 'mobile_phone', label: 'Mobile Phone' },
    { key: 'fax', label: 'Fax' },
    { key: 'address_line', label: 'Address' },
    { key: 'city', label: 'City' },
    { key: 'state', label: 'State' },
    { key: 'zip_code', label: 'Zip Code' },
    { key: 'country', label: 'Country' },
    { key: 'is_active', label: 'Active' },
    { key: 'primary_contact', label: 'Primary Contact' },
    { 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">Contacts Browser</h1>
          <p className="text-sm text-muted-foreground">Browse and inspect contact data</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Contacts</CardTitle>
          <CardDescription>
            {totalCount} total contacts in database
          </CardDescription>
        </CardHeader>
        <CardContent>
          <DataTable
            columns={columns}
            data={contacts}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchContacts(page, undefined, column, direction)}
            onSearch={(query) => fetchContacts(1, query)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
          />
        </CardContent>
      </Card>

      <DetailModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        title={`Contact: ${selectedContact?.first_name} ${selectedContact?.last_name}`}
        data={selectedContact}
        fields={detailFields}
      />
    </div>
  );
}
