'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, Table2 } from 'lucide-react';
import Link from 'next/link';
import { useUserTimezone } from '@/lib/hooks/use-user-timezone';

export default function ContractsBrowserPage() {
  const tz = useUserTimezone();
  const [contracts, setContracts] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(50);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedContract, setSelectedContract] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);

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

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

  const handleRowClick = (contract: any) => {
    setSelectedContract(contract);
    setModalOpen(true);
  };

  const columns = [
    {
      key: 'id',
      label: 'ID',
      sortable: true,
    },
    {
      key: 'contract_name',
      label: 'Contract Name',
      sortable: true,
      render: (value: string) => (
        <div className="font-medium">{value}</div>
      ),
    },
    {
      key: 'contract_number',
      label: 'Contract #',
      sortable: true,
    },
    {
      key: 'company_id',
      label: 'Company ID',
      sortable: true,
    },
    {
      key: 'status',
      label: 'Status',
      sortable: true,
    },
    {
      key: 'start_date',
      label: 'Start Date',
      sortable: true,
      render: (value: string) => (
        value ? new Date(value).toLocaleDateString(undefined, { timeZone: tz }) : '-'
      ),
    },
    {
      key: 'end_date',
      label: 'End Date',
      sortable: true,
      render: (value: string) => (
        value ? new Date(value).toLocaleDateString(undefined, { timeZone: tz }) : '-'
      ),
    },
  ];

  const detailFields = [
    { key: 'id', label: 'ID' },
    { key: 'company_id', label: 'Company ID' },
    { key: 'contract_name', label: 'Contract Name' },
    { key: 'contract_number', label: 'Contract Number' },
    { key: 'description', label: 'Description' },
    { key: 'status', label: 'Status' },
    { key: 'contract_type', label: 'Type' },
    { key: 'contract_category', label: 'Category' },
    { key: 'start_date', label: 'Start Date' },
    { key: 'end_date', label: 'End Date' },
    { key: 'estimated_cost', label: 'Estimated Cost' },
    { key: 'estimated_hours', label: 'Estimated Hours' },
    { key: 'estimated_revenue', label: 'Estimated Revenue' },
    { key: 'contact_id', label: 'Contact ID' },
    { key: 'contact_name', label: 'Contact Name' },
    { key: 'is_default_contract', label: 'Default Contract' },
    { 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-purple-100 dark:bg-purple-950">
              <Table2 className="w-5 h-5 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold tracking-tight">Contracts</h1>
              <p className="text-sm text-muted-foreground">Manage and inspect contract 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 Contracts</CardTitle>
              <CardDescription className="mt-1">
                View and search through all contracts in the system
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6">
          <DataTable
            columns={columns}
            data={contracts}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchContracts(page, undefined, column, direction)}
            onSearch={(query) => fetchContracts(1, query)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
          />
        </CardContent>
      </Card>

      {/* Detail Modal */}
      <DetailModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        title={selectedContract?.contract_name || 'Contract Details'}
        data={selectedContract}
        fields={detailFields}
      />
    </div>
  );
}
