import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { MainLayout } from '@/components/layout/MainLayout.tsx';
import PageHeader from '@/components/layout/PageHeader.tsx';
import ResourceFlowList from '@/components/resource-flow/ResourceFlowList.tsx';
import ResourceFlowWizard from '@/components/resource-flow/ResourceFlowWizard.tsx';
import { Container, Flex, Stack } from '@/components/ui/layout';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card.tsx';
import Button from '@/components/ui/Button.tsx';
import Select from '@/components/ui/Select.tsx';
import { useTranslation } from '@/hooks/useI18n.tsx';
import { useOrganizations } from '@/hooks/useOrganizations.ts';
import { useNavigation } from '@/hooks/useNavigation.tsx';
import type { BackendOrganization } from '@/schemas/backend/organization';
import type { ResourceDirection } from '@/schemas/backend/resource-flow';

const ResourceFlowsPage = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { handleBackNavigation, handleFooterNavigate } = useNavigation();
  const { organizations, isLoading: isLoadingOrgs } = useOrganizations();

  const [selectedOrganizationId, setSelectedOrganizationId] = useState<string>('');
  const [isWizardOpen, setIsWizardOpen] = useState(false);
  const [wizardDirection, setWizardDirection] = useState<ResourceDirection>('input');

  // Get selected organization details
  const selectedOrganization = useMemo(() => {
    return organizations?.find(org => org.ID === selectedOrganizationId) || null;
  }, [organizations, selectedOrganizationId]);

  const handleAddResourceFlow = (direction: ResourceDirection) => {
    if (!selectedOrganizationId) {
      // If no organization selected, show organization selector or redirect
      return;
    }
    setWizardDirection(direction);
    setIsWizardOpen(true);
  };

  const handleViewMatches = (resourceId: string) => {
    navigate(`/resource-flow/${resourceId}/matches`);
  };

  const handleWizardClose = () => {
    setIsWizardOpen(false);
  };

  const handleWizardSuccess = () => {
    setIsWizardOpen(false);
    // Optionally refresh data or show success message
  };

  const organizationOptions = useMemo(() => {
    return organizations?.map(org => ({
      value: org.ID,
      label: org.Name,
    })) || [];
  }, [organizations]);

  return (
    <MainLayout onNavigate={handleFooterNavigate} className="bg-muted/30">
      <Container size="2xl" className="py-8 sm:py-12">
        <PageHeader
          title={t('resourceFlows.title')}
          subtitle={t('resourceFlows.subtitle')}
          onBack={handleBackNavigation}
        />

        <Stack spacing="2xl">
          {/* Organization Selector */}
          <Card>
            <CardHeader>
              <CardTitle>{t('resourceFlows.selectOrganization')}</CardTitle>
            </CardHeader>
            <CardContent>
              <Flex gap="md" align="end">
                <div className="flex-1">
                  <label htmlFor="organization-select" className="block text-sm font-medium mb-2">
                    {t('resourceFlows.organization')}
                  </label>
                  <Select
                    id="organization-select"
                    value={selectedOrganizationId}
                    onValueChange={setSelectedOrganizationId}
                    options={organizationOptions}
                    placeholder={t('resourceFlows.selectOrganizationPlaceholder')}
                    disabled={isLoadingOrgs}
                  />
                </div>
                {selectedOrganization && (
                  <Flex gap="xs">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleAddResourceFlow('input')}
                    >
                      {t('resourceFlows.addInput')}
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleAddResourceFlow('output')}
                    >
                      {t('resourceFlows.addOutput')}
                    </Button>
                  </Flex>
                )}
              </Flex>
            </CardContent>
          </Card>

          {/* Resource Flows List */}
          {selectedOrganizationId ? (
            <ResourceFlowList
              organizationId={selectedOrganizationId}
              onAddResourceFlow={handleAddResourceFlow}
              onViewMatches={handleViewMatches}
            />
          ) : (
            <Card>
              <CardContent className="py-12">
                <div className="text-center">
                  <p className="text-muted-foreground mb-4">
                    {t('resourceFlows.selectOrganizationToView')}
                  </p>
                  <Button
                    variant="outline"
                    onClick={() => navigate('/organizations')}
                  >
                    {t('resourceFlows.viewAllOrganizations')}
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}
        </Stack>

        {/* Resource Flow Creation Wizard */}
        {selectedOrganization && (
          <ResourceFlowWizard
            isOpen={isWizardOpen}
            onClose={handleWizardClose}
            onSuccess={handleWizardSuccess}
            organizationId={selectedOrganizationId}
            organizationName={selectedOrganization.Name}
            direction={wizardDirection}
          />
        )}
      </Container>
    </MainLayout>
  );
};

export default ResourceFlowsPage;
