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

export default function SubIssueTypesBrowserPage() {
  const [subIssueTypes, setSubIssueTypes] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(100);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedSubIssueType, setSelectedSubIssueType] = useState<any>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [hideInactive, setHideInactive] = useState(false);

  const fetchSubIssueTypes = async (currentPage: number, search?: string, sortBy?: string, sortOrder?: string, activeOnly?: boolean) => {
    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);
      if (activeOnly !== undefined) params.append('isActive', activeOnly.toString());

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

  useEffect(() => {
    fetchSubIssueTypes(page, undefined, undefined, undefined, hideInactive);
  }, [page, hideInactive]);

  const handleToggleInactive = () => {
    setHideInactive(!hideInactive);
    setPage(1); // Reset to first page when toggling
  };

  const handleRowClick = (subIssueType: any) => {
    setSelectedSubIssueType(subIssueType);
    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: 'parent_issue_type_label',
      label: 'Parent Issue Type',
      sortable: true,
      render: (value: string, row: any) => (
        <div>
          {value ? (
            <Badge variant="outline">{value}</Badge>
          ) : row.parent_value ? (
            <Badge variant="secondary">ID: {row.parent_value}</Badge>
          ) : (
            <Badge variant="secondary">None</Badge>
          )}
        </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: 'parent_issue_type_label', label: 'Parent Issue Type' },
    { key: 'parent_value', label: 'Parent Issue Type Value' },
    { key: 'is_active', label: 'Active' },
    { key: 'is_system', label: 'System' },
    { key: 'sort_order', label: 'Sort Order' },
    { 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">Sub-Issue Types Browser</h1>
          <p className="text-sm text-muted-foreground">Browse sub-issue type picklist values</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Sub-Issue Types</CardTitle>
              <CardDescription>
                {totalCount} total sub-issue types {hideInactive ? '(active only)' : 'in database'}
              </CardDescription>
            </div>
            <Button
              variant={hideInactive ? "default" : "outline"}
              size="sm"
              onClick={handleToggleInactive}
              className="flex items-center gap-2"
            >
              {hideInactive ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
              {hideInactive ? 'Show All' : 'Hide Inactive'}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <DataTable
            columns={columns}
            data={subIssueTypes}
            totalCount={totalCount}
            page={page}
            pageSize={pageSize}
            onPageChange={setPage}
            onSort={(column, direction) => fetchSubIssueTypes(page, undefined, column, direction, hideInactive)}
            onSearch={(query) => fetchSubIssueTypes(1, query, undefined, undefined, hideInactive)}
            onRowClick={handleRowClick}
            isLoading={isLoading}
          />
        </CardContent>
      </Card>

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