'use client'

import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Filter, ClipboardCheck, Zap, Info } from 'lucide-react'
import {
  type FilteringRoundSettings,
  type EvaluationRoundSettings,
  type LiveEventRoundSettings,
  defaultFilteringSettings,
  defaultEvaluationSettings,
  defaultLiveEventSettings,
  roundTypeLabels,
  roundTypeDescriptions,
} from '@/types/round-settings'

interface RoundTypeSettingsProps {
  roundType: 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT'
  onRoundTypeChange: (type: 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT') => void
  settings: Record<string, unknown>
  onSettingsChange: (settings: Record<string, unknown>) => void
}

const roundTypeIcons = {
  FILTERING: Filter,
  EVALUATION: ClipboardCheck,
  LIVE_EVENT: Zap,
}

export function RoundTypeSettings({
  roundType,
  onRoundTypeChange,
  settings,
  onSettingsChange,
}: RoundTypeSettingsProps) {
  const Icon = roundTypeIcons[roundType]

  // Get typed settings with defaults
  const getFilteringSettings = (): FilteringRoundSettings => ({
    ...defaultFilteringSettings,
    ...(settings as Partial<FilteringRoundSettings>),
  })

  const getEvaluationSettings = (): EvaluationRoundSettings => ({
    ...defaultEvaluationSettings,
    ...(settings as Partial<EvaluationRoundSettings>),
  })

  const getLiveEventSettings = (): LiveEventRoundSettings => ({
    ...defaultLiveEventSettings,
    ...(settings as Partial<LiveEventRoundSettings>),
  })

  const updateSetting = <T extends Record<string, unknown>>(
    key: keyof T,
    value: T[keyof T]
  ) => {
    onSettingsChange({ ...settings, [key]: value })
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Icon className="h-5 w-5" />
          Round Type & Configuration
        </CardTitle>
        <CardDescription>
          Configure the type and behavior for this round
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Round Type Selector */}
        <div className="space-y-2">
          <Label>Round Type</Label>
          <Select value={roundType} onValueChange={(v) => onRoundTypeChange(v as typeof roundType)}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {(['FILTERING', 'EVALUATION', 'LIVE_EVENT'] as const).map((type) => {
                const TypeIcon = roundTypeIcons[type]
                return (
                  <SelectItem key={type} value={type}>
                    <div className="flex items-center gap-2">
                      <TypeIcon className="h-4 w-4" />
                      {roundTypeLabels[type]}
                    </div>
                  </SelectItem>
                )
              })}
            </SelectContent>
          </Select>
          <p className="text-sm text-muted-foreground">
            {roundTypeDescriptions[roundType]}
          </p>
        </div>

        {/* Type-specific settings */}
        {roundType === 'FILTERING' && (
          <FilteringSettings
            settings={getFilteringSettings()}
            onChange={(s) => onSettingsChange(s as unknown as Record<string, unknown>)}
          />
        )}

        {roundType === 'EVALUATION' && (
          <EvaluationSettings
            settings={getEvaluationSettings()}
            onChange={(s) => onSettingsChange(s as unknown as Record<string, unknown>)}
          />
        )}

        {roundType === 'LIVE_EVENT' && (
          <LiveEventSettings
            settings={getLiveEventSettings()}
            onChange={(s) => onSettingsChange(s as unknown as Record<string, unknown>)}
          />
        )}
      </CardContent>
    </Card>
  )
}

// Filtering Round Settings
function FilteringSettings({
  settings,
  onChange,
}: {
  settings: FilteringRoundSettings
  onChange: (settings: FilteringRoundSettings) => void
}) {
  return (
    <div className="space-y-6 border-t pt-4">
      <h4 className="font-medium">Filtering Settings</h4>

      {/* Target Advancing */}
      <div className="space-y-2">
        <Label htmlFor="targetAdvancing">Target Projects to Advance</Label>
        <Input
          id="targetAdvancing"
          type="number"
          min="1"
          value={settings.targetAdvancing}
          onChange={(e) =>
            onChange({ ...settings, targetAdvancing: parseInt(e.target.value) || 0 })
          }
        />
        <p className="text-xs text-muted-foreground">
          The target number of projects to advance to the next round
        </p>
      </div>

      {/* Auto-elimination */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <Label>Auto-Elimination</Label>
            <p className="text-sm text-muted-foreground">
              Automatically flag projects below threshold
            </p>
          </div>
          <Switch
            checked={settings.autoEliminationEnabled}
            onCheckedChange={(v) =>
              onChange({ ...settings, autoEliminationEnabled: v })
            }
          />
        </div>

        {settings.autoEliminationEnabled && (
          <div className="ml-6 space-y-4 border-l-2 pl-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="threshold">Score Threshold</Label>
                <Input
                  id="threshold"
                  type="number"
                  min="1"
                  max="10"
                  step="0.5"
                  value={settings.autoEliminationThreshold}
                  onChange={(e) =>
                    onChange({
                      ...settings,
                      autoEliminationThreshold: parseFloat(e.target.value) || 0,
                    })
                  }
                />
                <p className="text-xs text-muted-foreground">
                  Projects averaging below this score will be flagged
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="minReviews">Minimum Reviews</Label>
                <Input
                  id="minReviews"
                  type="number"
                  min="1"
                  value={settings.autoEliminationMinReviews}
                  onChange={(e) =>
                    onChange({
                      ...settings,
                      autoEliminationMinReviews: parseInt(e.target.value) || 1,
                    })
                  }
                />
                <p className="text-xs text-muted-foreground">
                  Min reviews before auto-elimination applies
                </p>
              </div>
            </div>

            <Alert>
              <Info className="h-4 w-4" />
              <AlertDescription>
                Auto-elimination only flags projects for review. Final decisions require
                admin approval.
              </AlertDescription>
            </Alert>
          </div>
        )}
      </div>

      {/* Display Options */}
      <div className="space-y-4">
        <h5 className="text-sm font-medium">Display Options</h5>
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="flex items-center justify-between">
            <Label htmlFor="showAverage">Show Average Score</Label>
            <Switch
              id="showAverage"
              checked={settings.showAverageScore}
              onCheckedChange={(v) =>
                onChange({ ...settings, showAverageScore: v })
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <Label htmlFor="showRanking">Show Ranking</Label>
            <Switch
              id="showRanking"
              checked={settings.showRanking}
              onCheckedChange={(v) =>
                onChange({ ...settings, showRanking: v })
              }
            />
          </div>
        </div>
      </div>
    </div>
  )
}

// Evaluation Round Settings
function EvaluationSettings({
  settings,
  onChange,
}: {
  settings: EvaluationRoundSettings
  onChange: (settings: EvaluationRoundSettings) => void
}) {
  return (
    <div className="space-y-6 border-t pt-4">
      <h4 className="font-medium">Evaluation Settings</h4>

      {/* Target Finalists */}
      <div className="space-y-2">
        <Label htmlFor="targetFinalists">Target Finalists</Label>
        <Input
          id="targetFinalists"
          type="number"
          min="1"
          value={settings.targetFinalists}
          onChange={(e) =>
            onChange({ ...settings, targetFinalists: parseInt(e.target.value) || 0 })
          }
        />
        <p className="text-xs text-muted-foreground">
          The target number of finalists to select
        </p>
      </div>

      {/* Requirements */}
      <div className="space-y-4">
        <h5 className="text-sm font-medium">Requirements</h5>

        <div className="flex items-center justify-between">
          <div>
            <Label>Require All Criteria</Label>
            <p className="text-sm text-muted-foreground">
              Jury must score all criteria before submission
            </p>
          </div>
          <Switch
            checked={settings.requireAllCriteria}
            onCheckedChange={(v) =>
              onChange({ ...settings, requireAllCriteria: v })
            }
          />
        </div>

        <div className="flex items-center justify-between">
          <div>
            <Label>Detailed Criteria Required</Label>
            <p className="text-sm text-muted-foreground">
              Use detailed evaluation criteria
            </p>
          </div>
          <Switch
            checked={settings.detailedCriteriaRequired}
            onCheckedChange={(v) =>
              onChange({ ...settings, detailedCriteriaRequired: v })
            }
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="minFeedback">Minimum Feedback Length</Label>
          <Input
            id="minFeedback"
            type="number"
            min="0"
            value={settings.minimumFeedbackLength}
            onChange={(e) =>
              onChange({
                ...settings,
                minimumFeedbackLength: parseInt(e.target.value) || 0,
              })
            }
          />
          <p className="text-xs text-muted-foreground">
            Minimum characters for feedback comments (0 = optional)
          </p>
        </div>
      </div>

      {/* Display Options */}
      <div className="space-y-4">
        <h5 className="text-sm font-medium">Display Options</h5>
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="flex items-center justify-between">
            <Label htmlFor="showAverage">Show Average Score</Label>
            <Switch
              id="showAverage"
              checked={settings.showAverageScore}
              onCheckedChange={(v) =>
                onChange({ ...settings, showAverageScore: v })
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <Label htmlFor="showRanking">Show Ranking</Label>
            <Switch
              id="showRanking"
              checked={settings.showRanking}
              onCheckedChange={(v) =>
                onChange({ ...settings, showRanking: v })
              }
            />
          </div>
        </div>
      </div>
    </div>
  )
}

// Live Event Round Settings
function LiveEventSettings({
  settings,
  onChange,
}: {
  settings: LiveEventRoundSettings
  onChange: (settings: LiveEventRoundSettings) => void
}) {
  return (
    <div className="space-y-6 border-t pt-4">
      <h4 className="font-medium">Live Event Settings</h4>

      {/* Presentation */}
      <div className="space-y-4">
        <h5 className="text-sm font-medium">Presentation</h5>

        <div className="space-y-2">
          <Label htmlFor="duration">Presentation Duration (minutes)</Label>
          <Input
            id="duration"
            type="number"
            min="1"
            max="60"
            value={settings.presentationDurationMinutes}
            onChange={(e) =>
              onChange({
                ...settings,
                presentationDurationMinutes: parseInt(e.target.value) || 5,
              })
            }
          />
        </div>
      </div>

      {/* Voting */}
      <div className="space-y-4">
        <h5 className="text-sm font-medium">Voting</h5>

        <div className="space-y-2">
          <Label htmlFor="votingWindow">Voting Window (seconds)</Label>
          <Input
            id="votingWindow"
            type="number"
            min="10"
            max="300"
            value={settings.votingWindowSeconds}
            onChange={(e) =>
              onChange({
                ...settings,
                votingWindowSeconds: parseInt(e.target.value) || 30,
              })
            }
          />
          <p className="text-xs text-muted-foreground">
            Duration of the voting window after each presentation
          </p>
        </div>

        <div className="flex items-center justify-between">
          <div>
            <Label>Allow Vote Change</Label>
            <p className="text-sm text-muted-foreground">
              Allow jury to change their vote during the window
            </p>
          </div>
          <Switch
            checked={settings.allowVoteChange}
            onCheckedChange={(v) =>
              onChange({ ...settings, allowVoteChange: v })
            }
          />
        </div>
      </div>

      {/* Display */}
      <div className="space-y-4">
        <h5 className="text-sm font-medium">Display</h5>

        <div className="flex items-center justify-between">
          <div>
            <Label>Show Live Scores</Label>
            <p className="text-sm text-muted-foreground">
              Display scores in real-time during the event
            </p>
          </div>
          <Switch
            checked={settings.showLiveScores}
            onCheckedChange={(v) =>
              onChange({ ...settings, showLiveScores: v })
            }
          />
        </div>

        <div className="space-y-2">
          <Label>Display Mode</Label>
          <Select
            value={settings.displayMode}
            onValueChange={(v) =>
              onChange({
                ...settings,
                displayMode: v as 'SCORES' | 'RANKING' | 'NONE',
              })
            }
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="SCORES">Show Scores</SelectItem>
              <SelectItem value="RANKING">Show Ranking</SelectItem>
              <SelectItem value="NONE">Hide Until End</SelectItem>
            </SelectContent>
          </Select>
          <p className="text-xs text-muted-foreground">
            How results are displayed on the public screen
          </p>
        </div>
      </div>

      <Alert>
        <Info className="h-4 w-4" />
        <AlertDescription>
          Presentation order can be configured in the Live Voting section once the round
          is activated.
        </AlertDescription>
      </Alert>
    </div>
  )
}
