'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 ResourcesBrowserPage() {
  const [resources, setResources] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(50);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedResource, setSelectedResource] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const fetchResources = async (currentPage: number, search?: string, sortBy?: string, sortOrder?: string) => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams({
        limit: pageSize.toString(),
        offset: ((currentPage - 1) * 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/resources?${params}`);
      const result = await response.json();
      
      setResources(result.resources || []);
      setTotalCount(result.pagination?.total || 0);
    } catch (error) {
      console.error('Failed to fetch resources:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleRowClick = (resource: any) => {
    setSelectedResource(resource);
    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,
      render: (value: string) => (
        <div className="font-medium">{value}</div>
      ),
    },
    {
      key: 'email',
      label: 'Email',
      sortable: true,
    },
    {
      key: 'title',
      label: 'Title',
    },
    {
      key: 'office_phone',
      label: 'Phone',
    },
    {
      key: 'is_active',
      label: 'Active',
      render: (value: boolean) => (
        <Badge variant={value ? 'default' : 'secondary'}>
          {value ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
  ];

  const detailFields = [
    { key: 'id', label: 'ID' },
    // Name fields
    { key: 'name_prefix', label: 'Prefix' },
    { key: 'first_name', label: 'First Name' },
    { key: 'middle_initial', label: 'Middle Initial' },
    { key: 'last_name', label: 'Last Name' },
    { key: 'name_suffix', label: 'Suffix' },
    // Contact information
    { key: 'email', label: 'Primary Email' },
    { key: 'email_address', label: 'Email Address' },
    { key: 'email_address2', label: 'Email Address 2' },
    { key: 'email_address3', label: 'Email Address 3' },
    { key: 'office_phone', label: 'Office Phone' },
    { key: 'mobile_phone', label: 'Mobile Phone' },
    { key: 'home_phone', label: 'Home Phone' },
    { key: 'office_extension', label: 'Extension' },
    // System fields
    { key: 'user_name', label: 'Username' },
    { key: 'title', label: 'Title' },
    { key: 'is_active', label: 'Active' },
    // Employment details
    { key: 'resource_type', label: 'Resource Type' },
    { key: 'payroll_identifier', label: 'Payroll Identifier' },
    { key: 'payroll_type', label: 'Payroll Type' },
    { key: 'accounting_reference_id', label: 'Accounting Reference ID' },
    { key: 'internal_cost', label: 'Internal Cost' },
    { key: 'hire_date', label: 'Hire Date' },
    // Location and availability
    { key: 'location_id', label: 'Location ID' },
    { key: 'travel_availability_pct', label: 'Travel Availability %' },
    { key: 'default_service_desk_role_id', label: 'Default Service Desk Role' },
    // System preferences
    { key: 'email_type_code', label: 'Email Type' },
    { key: 'number_format', label: 'Number Format' },
    { key: 'time_format', label: 'Time Format' },
    { key: 'date_format', label: 'Date Format' },
    // Demographics and security
    { key: 'gender', label: 'Gender' },
    { key: 'license_type', label: 'License Type' },
    { key: 'security_level', label: 'Security Level' },
    // Ratings
    { key: 'survey_resource_rating', label: 'Survey Rating' },
    // Audit fields
    { key: 'synced_at', label: 'Synced At' },
    { key: 'is_deleted', label: 'Is Deleted' },
  ];

  return (
    <div className="container mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <Link href="/admin/data-browser">
            <Button variant="outline" size="sm" className="gap-2">
              <ArrowLeft className="w-4 h-4" />
              Back
            </Button>
          </Link>
          <div className="h-8 w-px bg-border" />
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-blue-100 dark:bg-blue-950">
              <Users className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold tracking-tight">Resources</h1>
              <p className="text-sm text-muted-foreground">Manage and inspect user data</p>
            </div>
          </div>
        </div>
        <Badge variant="secondary" className="w-fit">
          {totalCount} total records
        </Badge>
      </div>

      {/* Data Table Card */}
      <Card className="border-none shadow-md">
        <CardHeader className="border-b bg-muted/30">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">All Resources</CardTitle>
              <CardDescription className="mt-1">
                View and search through all resources in the system
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6">
          <DataTable
            columns={columns}
            data={resources}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchResources(page, undefined, column, direction)}
            onSearch={(query) => fetchResources(1, query)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
          />
        </CardContent>
      </Card>

      {/* Detail Modal */}
      <DetailModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        title={`${selectedResource?.first_name} ${selectedResource?.last_name}`}
        data={selectedResource}
        fields={detailFields}
      />
    </div>
  );
}
