// components/baselineRatematrix/RateMatrixForm.tsx
import React, { useState, useCallback } from 'react';
// import { useForm } from 'react-hook-form';
// import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Loader2, Save, Send, Shield, AlertTriangle } from 'lucide-react';
import { RateTypeSection } from './RateTypeSection';
import { ConfirmationDialog } from './ConfirmationDialog';
import { ValidationSummary } from './ValidationSummary';
import { LoadingScreen } from '@/ui/LoadingScreen';
import { useRateMatrixAuth } from '@/auth/hooks/useAuth';
import { useReferenceData } from '@/hooks/useReferenceData';
import { queryKeys } from '@/constants/queryKeys';
import { API_URLS } from '@/constants/apiUrls';
import { 
  RATE_TYPES, 
  RATE_TYPE_LABELS, 
  REQUIRED_RATE_TYPES 
} from '@/constants/rateMatrixConstants';
import { rateMatrixRulesEngine } from '../../ruleEngine/rateMatrixRules';
import type { RateEntry } from './types';

const formSchema = z.object({
  matrixName: z.string().min(1, 'Matrix name is required').max(200),
  effectiveDate: z.string().min(1, 'Effective date is required'),
  expiryDate: z.string().optional(),
  currency: z.string().min(1, 'Currency is required'),
});

type FormData = z.infer<typeof formSchema>;

const createInitialSections = (): RateEntry[] => {
  return REQUIRED_RATE_TYPES.map(rateType => ({
    rateType,
    entries: [{
      validFrom: '',
      validTo: '',
    }],
  }));
};

export function RateMatrixForm() {
  const [rateSections, setRateSections] = useState<RateEntry[]>(createInitialSections());
  const [showConfirmation, setShowConfirmation] = useState(false);
  const [savedMatrixId, setSavedMatrixId] = useState<string | null>(null);
  const [validationErrors, setValidationErrors] = useState<any[]>([]);
  
  const { isDirector } = useRateMatrixAuth();
  const { data: referenceData, isLoading: isLoadingReference } = useReferenceData();
  const queryClient = useQueryClient();

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      matrixName: '',
      effectiveDate: '',
      expiryDate: '',
      currency: 'USD',
    },
  });

  // Save draft mutation
  const saveDraftMutation = useMutation({
    mutationFn: async (data: FormData & { rateSections: RateEntry[] }) => {
      const response = await fetch(API_URLS.RATE_MATRIX.DRAFT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      if (!response.ok) throw new Error('Failed to save draft');
      return response.json();
    },
    onSuccess: (data) => {
      setSavedMatrixId(data.id);
      queryClient.invalidateQueries({ queryKey: queryKeys.rateMatrix.all });
      toast.success('Draft saved successfully');
    },
    onError: (error) => {
      toast.error('Failed to save draft');
    },
  });

  // Submit for approval mutation
  const submitMutation = useMutation({
    mutationFn: async (matrixId: string) => {
      const response = await fetch(API_URLS.RATE_MATRIX.SUBMIT(matrixId), {
        method: 'POST',
      });
      if (!response.ok) throw new Error('Failed to submit');
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.rateMatrix.all });
      toast.success('Rate matrix submitted for executive approval and locked!');
      setShowConfirmation(false);
    },
    onError: (error) => {
      toast.error('Failed to submit for approval');
      setShowConfirmation(false);
    },
  });

  const handleValidate = useCallback(() => {
    const validation = rateMatrixRulesEngine.validate(rateSections);
    setValidationErrors([...validation.errors, ...validation.warnings]);
    
    if (validation.isValid) {
      toast.success('All validations passed!');
    }
  }, [rateSections]);

  const handleSaveDraft = async () => {
    const formData = form.getValues();
    await saveDraftMutation.mutateAsync({
      ...formData,
      rateSections,
    });
  };

  const handleSubmitClick = async () => {
    const isFormValid = await form.trigger();
    if (!isFormValid) return;

    const validation = rateMatrixRulesEngine.validate(rateSections);
    setValidationErrors([...validation.errors, ...validation.warnings]);
    
    if (!validation.isValid) {
      toast.error('Please fix validation errors before submitting');
      return;
    }

    setShowConfirmation(true);
  };

  const handleConfirmSubmit = async () => {
    const formData = form.getValues();
    
    try {
      let matrixId = savedMatrixId;
      
      if (!matrixId) {
        const draftResult = await saveDraftMutation.mutateAsync({
          ...formData,
          rateSections,
        });
        matrixId = draftResult.id;
      }

      await submitMutation.mutateAsync(matrixId!);
    } catch (error) {
      // Error handling done in mutations
    }
  };

  if (isLoadingReference) {
    return <LoadingScreen message="Loading reference data..." />;
  }

  if (!isDirector) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Alert variant="destructive" className="max-w-md">
          <AlertTriangle className="h-4 w-4" />
          <AlertTitle>Access Denied</AlertTitle>
          <AlertDescription>
            Only Directors can access the rate matrix registration.
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 px-4 max-w-7xl">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold tracking-tight">
          Baseline Rate Matrix Registration
        </h1>
        <p className="text-muted-foreground mt-2">
          Submit a comprehensive rate matrix for executive approval
        </p>
      </div>

      {/* Director Warning */}
      <Alert variant="warning" className="mb-6 border-amber-500 bg-amber-50">
        <Shield className="h-4 w-4" />
        <AlertTitle>Director Notice</AlertTitle>
        <AlertDescription>
          Once submitted, this matrix will be locked pending Chief Executive approval. 
          No edits can be made by any user until authorization is granted.
        </AlertDescription>
      </Alert>

      <form onSubmit={(e) => e.preventDefault()}>
        {/* Matrix Metadata */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Matrix Information</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="space-y-2">
                <Label htmlFor="matrixName">Matrix Name *</Label>
                <Input
                  id="matrixName"
                  {...form.register('matrixName')}
                  placeholder="e.g., Q4 2026 Baseline Matrix"
                  className={form.formState.errors.matrixName ? 'border-destructive' : ''}
                />
                {form.formState.errors.matrixName && (
                  <p className="text-sm text-destructive">
                    {form.formState.errors.matrixName.message}
                  </p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="effectiveDate">Effective Date *</Label>
                <Input
                  id="effectiveDate"
                  type="date"
                  {...form.register('effectiveDate')}
                  className={form.formState.errors.effectiveDate ? 'border-destructive' : ''}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="expiryDate">Expiry Date</Label>
                <Input
                  id="expiryDate"
                  type="date"
                  {...form.register('expiryDate')}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="currency">Currency *</Label>
                <select
                  id="currency"
                  {...form.register('currency')}
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2"
                >
                  {referenceData?.currencies?.map((currency: any) => (
                    <option key={currency.code} value={currency.code}>
                      {currency.code} - {currency.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Rate Type Sections */}
        <div className="space-y-6">
          {rateSections.map((section, index) => (
            <RateTypeSection
              key={section.rateType}
              section={section}
              sectionIndex={index}
              onUpdate={(updatedSection) => {
                const newSections = [...rateSections];
                newSections[index] = updatedSection;
                setRateSections(newSections);
              }}
              referenceData={referenceData}
            />
          ))}
        </div>

        {/* Validation Errors */}
        {validationErrors.length > 0 && (
          <div className="mt-6">
            <ValidationSummary errors={validationErrors} />
          </div>
        )}

        {/* Form Actions */}
        <div className="sticky bottom-6 mt-8 p-6 bg-background border rounded-lg shadow-lg flex gap-4 justify-end">
          <Button
            type="button"
            variant="outline"
            onClick={handleSaveDraft}
            disabled={saveDraftMutation.isPending}
          >
            {saveDraftMutation.isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            Save as Draft
          </Button>
          
          <Button
            type="button"
            variant="secondary"
            onClick={handleValidate}
          >
            Validate All Rates
          </Button>
          
          <Button
            type="button"
            onClick={handleSubmitClick}
            disabled={submitMutation.isPending}
          >
            <Send className="mr-2 h-4 w-4" />
            Submit for Executive Approval
          </Button>
        </div>
      </form>

      {/* Confirmation Dialog */}
      <ConfirmationDialog
        open={showConfirmation}
        onOpenChange={setShowConfirmation}
        onConfirm={handleConfirmSubmit}
        isLoading={submitMutation.isPending}
      />
    </div>
  );
}