'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, Tag } from 'lucide-react';
import Link from 'next/link';

export default function IssueTypesBrowserPage() {
  const [issueTypes, setIssueTypes] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(100);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedIssueType, setSelectedIssueType] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);

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

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

  const handleRowClick = (issueType: any) => {
    setSelectedIssueType(issueType);
    setModalOpen(true);
  };

  const columns = [
    {
      key: 'value',
      label: 'Value',
      sortable: true,
    },
    {
      key: 'label',
      label: 'Label',
      sortable: true,
      render: (value: string) => (
        <div className="font-medium">{value}</div>
      ),
    },
    {
      key: 'is_active',
      label: 'Active',
      render: (value: boolean) => (
        <Badge variant={value ? 'default' : 'secondary'}>
          {value ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
    {
      key: 'is_system',
      label: 'System',
      render: (value: boolean) => (
        <Badge variant={value ? 'outline' : 'secondary'}>
          {value ? 'System' : 'Custom'}
        </Badge>
      ),
    },
    {
      key: 'sort_order',
      label: 'Sort Order',
      sortable: true,
    },
  ];

  const detailFields = [
    { key: 'value', label: 'Value' },
    { key: 'label', label: 'Label' },
    { key: 'is_active', label: 'Active' },
    { key: 'is_system', label: 'System' },
    { key: 'sort_order', label: 'Sort Order' },
    { key: 'parent_value', label: 'Parent Value' },
    { key: 'synced_at', label: 'Synced At' },
  ];

  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>
        <Tag className="w-6 h-6" />
        <div>
          <h1 className="text-2xl font-bold">Issue Types Browser</h1>
          <p className="text-sm text-muted-foreground">Browse issue type picklist values</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Issue Types</CardTitle>
          <CardDescription>
            {totalCount} total issue types in database
          </CardDescription>
        </CardHeader>
        <CardContent>
          <DataTable
            columns={columns}
            data={issueTypes}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchIssueTypes(page, undefined, column, direction)}
            onSearch={(query) => fetchIssueTypes(1, query)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
          />
        </CardContent>
      </Card>

      <DetailModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        title={`Issue Type: ${selectedIssueType?.label}`}
        data={selectedIssueType}
        fields={detailFields}
      />
    </div>
  );
}
