'use client';

import { useState, useMemo } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/Input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { InfoIcon, AlertTriangleIcon, CheckCircleIcon } from 'lucide-react';

// Import orchestration engine (would be from API in production)
import type { 
  OrchestrationRequest, 
  OrchestrationResult,
  OutputType,
  InputSpec,
  TimelineSpec
} from '@/lib/fairness-orchestration';
import { orchestrate, getAvailableOutputs, getUserMessage } from '@/lib/fairness-orchestration';

export default function FairnessOrchestrationWizard() {
  const [selectedOutputs, setSelectedOutputs] = useState<string[]>([]);
  const [inputSpec, setInputSpec] = useState<InputSpec>({
    dataset: '',
    sensitiveAttributes: [],
    dateRange: undefined,
    filters: {}
  });
  const [timeline, setTimeline] = useState<TimelineSpec>({
    mode: 'now',
    sla: '2 hours'
  });
  const [orchestrationResult, setOrchestrationResult] = useState<OrchestrationResult | null>(null);

  const availableOutputs = getAvailableOutputs();

  // Calculate orchestration when inputs change
  const result = useMemo(() => {
    if (!inputSpec.dataset || selectedOutputs.length === 0) {
      return null;
    }

    const request: OrchestrationRequest = {
      input: inputSpec,
      outputs: selectedOutputs,
      timeline
    };

    return orchestrate(request);
  }, [inputSpec, selectedOutputs, timeline]);

  const handleOutputToggle = (outputId: string) => {
    setSelectedOutputs(prev => 
      prev.includes(outputId)
        ? prev.filter(id => id !== outputId)
        : [...prev, outputId]
    );
  };

  const handleRun = () => {
    if (result) {
      setOrchestrationResult(result);
    }
  };

  return (
    <div className="space-y-6 p-6">
      <div>
        <h1 className="text-3xl font-bold">Fairness Audit Orchestration</h1>
        <p className="text-muted-foreground mt-2">
          Design from the end result backwards. Choose your outputs, inputs, and timeline.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Step 1: Output Selection */}
        <Card>
          <CardHeader>
            <CardTitle>1. Output</CardTitle>
            <CardDescription>What do you want to generate?</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {availableOutputs.map((output) => (
              <div key={output.id} className="flex items-start space-x-3">
                <Checkbox
                  id={output.id}
                  checked={selectedOutputs.includes(output.id)}
                  onCheckedChange={() => handleOutputToggle(output.id)}
                />
                <div className="flex-1">
                  <Label htmlFor={output.id} className="font-medium cursor-pointer">
                    {output.name}
                  </Label>
                  <p className="text-sm text-muted-foreground">
                    {output.description}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    Weight: {output.weight} units
                  </p>
                </div>
              </div>
            ))}
            {selectedOutputs.length > 0 && (
              <div className="pt-4 border-t">
                <p className="text-sm">
                  <strong>Total Output Load:</strong>{' '}
                  {result?.outputLoad.toFixed(1) || '0'} units
                </p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Step 2: Input Specification */}
        <Card>
          <CardHeader>
            <CardTitle>2. Input</CardTitle>
            <CardDescription>What data are you analyzing?</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="dataset">Dataset</Label>
              <Input
                id="dataset"
                value={inputSpec.dataset}
                onChange={(e) => setInputSpec(prev => ({ ...prev, dataset: e.target.value }))}
                placeholder="Select or enter dataset name"
              />
            </div>

            <div>
              <Label htmlFor="dateRange">Date Range (Optional)</Label>
              <div className="grid grid-cols-2 gap-2">
                <Input
                  type="date"
                  value={inputSpec.dateRange?.start || ''}
                  onChange={(e) => setInputSpec(prev => ({
                    ...prev,
                    dateRange: { ...prev.dateRange, start: e.target.value } as any
                  }))}
                />
                <Input
                  type="date"
                  value={inputSpec.dateRange?.end || ''}
                  onChange={(e) => setInputSpec(prev => ({
                    ...prev,
                    dateRange: { ...prev.dateRange, end: e.target.value } as any
                  }))}
                />
              </div>
            </div>

            <div>
              <Label htmlFor="sensitiveAttributes">Sensitive Attributes</Label>
              <Input
                id="sensitiveAttributes"
                value={inputSpec.sensitiveAttributes.join(', ')}
                onChange={(e) => setInputSpec(prev => ({
                  ...prev,
                  sensitiveAttributes: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
                }))}
                placeholder="race, gender, age (comma-separated)"
              />
            </div>

            {result && (
              <div className="pt-4 border-t">
                <p className="text-sm">
                  <strong>Estimated Input Load:</strong>{' '}
                  {result.inputLoad.toFixed(0)} units
                </p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Step 3: Timeline */}
        <Card>
          <CardHeader>
            <CardTitle>3. Timeline</CardTitle>
            <CardDescription>When does this need to be ready?</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="mode">Execution Mode</Label>
              <Select
                value={timeline.mode}
                onValueChange={(value: 'now' | 'scheduled' | 'continuous') =>
                  setTimeline(prev => ({ ...prev, mode: value }))
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="now">Run Now</SelectItem>
                  <SelectItem value="scheduled">Schedule</SelectItem>
                  <SelectItem value="continuous">Continuous</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="sla">SLA / Time Limit</Label>
              <Input
                id="sla"
                value={timeline.sla || ''}
                onChange={(e) => setTimeline(prev => ({ ...prev, sla: e.target.value }))}
                placeholder="2 hours, 1 day, 30 minutes"
              />
            </div>

            {result && (
              <div className="pt-4 border-t space-y-2">
                <p className="text-sm">
                  <strong>Estimated Time:</strong>{' '}
                  {formatTime(result.estimatedTime)}
                </p>
                <p className="text-sm">
                  <strong>Total Process Load:</strong>{' '}
                  {result.totalLoad.toFixed(1)} units
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Orchestration Result */}
      {result && (
        <Card>
          <CardHeader>
            <CardTitle>Orchestration Analysis</CardTitle>
            <CardDescription>
              The engine calculates: Total Load ≈ Output + 2×Input ≈ 3.2×Input
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-3 gap-4">
              <div>
                <p className="text-sm text-muted-foreground">Input Load</p>
                <p className="text-2xl font-bold">{result.inputLoad.toFixed(0)}</p>
                <p className="text-xs text-muted-foreground">× 2 = {result.inputLoad * 2} (passes)</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Output Load</p>
                <p className="text-2xl font-bold">{result.outputLoad.toFixed(1)}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Total Load</p>
                <p className="text-2xl font-bold">{result.totalLoad.toFixed(1)}</p>
                <p className="text-xs text-muted-foreground">
                  ≈ {result.inputLoad.toFixed(0)} × 3.2 = {(result.inputLoad * 3.2).toFixed(1)}
                </p>
              </div>
            </div>

            {result.warnings.length > 0 && (
              <Alert variant={result.feasible ? 'default' : 'destructive'}>
                <AlertTriangleIcon className="h-4 w-4" />
                <AlertDescription>
                  <div className="space-y-2">
                    {result.warnings.map((warning, i) => (
                      <p key={i}>{warning}</p>
                    ))}
                  </div>
                </AlertDescription>
              </Alert>
            )}

            {result.suggestions.length > 0 && (
              <Alert>
                <InfoIcon className="h-4 w-4" />
                <AlertDescription>
                  <div className="space-y-1">
                    <p className="font-medium">Suggestions:</p>
                    {result.suggestions.map((suggestion, i) => (
                      <p key={i} className="text-sm">• {suggestion}</p>
                    ))}
                  </div>
                </AlertDescription>
              </Alert>
            )}

            {result.feasible && result.warnings.length === 0 && (
              <Alert variant="default" className="border-green-500">
                <CheckCircleIcon className="h-4 w-4 text-green-500" />
                <AlertDescription className="text-green-700">
                  This configuration is feasible and ready to run.
                </AlertDescription>
              </Alert>
            )}

            <div className="pt-4">
              <p className="text-sm text-muted-foreground mb-2">
                {getUserMessage(result, {
                  input: inputSpec,
                  outputs: selectedOutputs,
                  timeline
                })}
              </p>
            </div>

            <Button
              onClick={handleRun}
              disabled={!result.feasible || selectedOutputs.length === 0 || !inputSpec.dataset}
              className="w-full"
            >
              {result.feasible ? 'Run Fairness Audit' : 'Adjust Configuration'}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Info Box */}
      <Card className="bg-muted/50">
        <CardContent className="pt-6">
          <div className="space-y-2">
            <h3 className="font-semibold">How It Works</h3>
            <p className="text-sm text-muted-foreground">
              <strong>We design from the end result backwards.</strong> First we list every output you want 
              (reports, files, metrics), then we calculate how much input validation and enrichment is needed 
              — roughly <strong>2× your input effort</strong> — and size the total job at about <strong>3.2× the input</strong>.
            </p>
            <p className="text-sm text-muted-foreground">
              You only choose: (1) What goes in, (2) What comes out, (3) When it needs to be ready.
              The orchestration engine does everything in between.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function formatTime(seconds: number): string {
  if (seconds < 60) return `${Math.ceil(seconds)}s`;
  if (seconds < 3600) return `${(seconds / 60).toFixed(1)}m`;
  if (seconds < 86400) return `${(seconds / 3600).toFixed(1)}h`;
  return `${(seconds / 86400).toFixed(1)}d`;
}

